Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exec bash shell function

Tags:

bash

shell

go

We have a large collection of shell functions for various uses that are added to our .bash_profiles and we use on a daily basis. We call the functions like regular binaries.

I am trying to call these same shell functions from inside a Go app but it cannot find them as it's obviously running in a different context and can't find these in my $PATH.

The error is: exec: "finderx": executable file not found in $PATH

Does anyone know how to execute shell commands from a Go app in the same context as the terminal it's running in? or maybe to re-source them some how I don't want to have to re-implement these functions if possible.
I'd like to just call them as we do from scripts to ease the transition period. We will be gradually moving everything across to Go, but for now, we have to live with the shell functions

like image 616
Cheyne Avatar asked Nov 15 '25 07:11

Cheyne


2 Answers

I guess you can simply invoke bash -l -c 'your alias function'. Just make sure that your .bash_aliases or another dotfile with your functions is sourced from .bashrc(which, by the way, should be sourced from .bash_profile, as non-interactive login shell doesn't read .bashrc).

like image 64
Alexander Zinchenko Avatar answered Nov 17 '25 21:11

Alexander Zinchenko


Create a wrapper script that can run command line arguments. Example:

/home/user/run.sh

#!/bin/sh
source ~/.bash_profile
$1

test.go

package main

import (
    "fmt"
    "os/exec"
)  

func main(){
    testCmd := exec.Command("/home/user/run.sh","func123")        
    testOut, err := testCmd.Output()
    if err != nil {
        panic(err)
    } 
    fmt.Println(string(testOut))
}
like image 31
Subbu M Avatar answered Nov 17 '25 20:11

Subbu M