How to execute a shell built-in command

后端 未结 2 721
耶瑟儿~
耶瑟儿~ 2021-01-04 21:49

I am trying to find out if a program exists on Linux and I found this article. I tried executing this from my go program and it keeps giving me an error saying it can-not fi

相关标签:
2条回答
  • 2021-01-04 22:24

    Just like that article says, "command" is a shell built-in. You can do this natively in go via exec.LookPath.

    If you must, you can either use the system which binary, or you can execute command from within a shell,

    exec.Command("/bin/bash", "-c", "command -v foo")
    
    0 讨论(0)
  • 2021-01-04 22:31

    Alternatively, if it is a built in command that doesn't need parameters you could do something like the following:

    package main
    
    import (
        "fmt"
        "log"
        "os/exec"
    )
    
    func main() {
        out, err := exec.Command("uuidgen").Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s", out)
    }
    

    This would print out a unique ID like the following : 4cdb277e-3c25-48ef-a367-ba734ce407c1 just like calling it directly from the command line.

    0 讨论(0)
提交回复
热议问题