doufan1363
doufan1363
2018-03-01 23:41

在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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dounai7148 dounai7148 3年前

    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 doudou890510 3年前

    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))
    }
    
    点赞 评论 复制链接分享

为你推荐