doufan1363
2018-03-01 23:41
浏览 173

在GoLang中执行bash shell函数?

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 GoLang 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 GoLang 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

图片转代码服务由CSDN问答提供 功能建议

我们有大量的shell函数用于各种用途,这些函数已添加到我们的.bash_profiles中,并且每天使用 基础。 我们将这些函数称为常规二进制文件。

我正在尝试从GoLang应用程序内部调用这些相同的shell函数,但由于它们显然在不同的上下文中运行并且无法找到它们,因此无法找到它们 在我的$ PATH中找到这些。

错误是: exec:“ finderx”:在$ PATH中找不到可执行文件

是否有人 知道如何在与运行终端相同的上下文中从GoLang应用执行shell命令? 或者也许可以重新获得它们一些我不希望在可能的情况下必须重新实现这些功能的方法。
我想像在脚本中那样调用它们,以缩短过渡期。 我们将逐步将所有内容转移到Go,但是现在,我们必须使用shell函数

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dounai7148 2018-03-02 01:51
    已采纳

    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).

    已采纳该答案
    打赏 评论
  • doudou890510 2018-03-02 01:31

    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))
    }
    
    打赏 评论

相关推荐 更多相似问题