13

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 find "command" in my $PATH, which is to be expected since it's a built-in command in linux and not a binary. So my question is how to execute built in commands of linux from within go programs?

exec.Command("command", "-v", "foo")

error: exec: "command": executable file not found in $PATH

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Konoha
  • 337
  • 1
  • 4
  • 13

2 Answers2

13

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")
JimB
  • 104,193
  • 13
  • 262
  • 255
  • For bash users, `type` is preferable over `which` (the latter is a script). – Rick-777 Dec 13 '15 at 11:21
  • Also note that bash had a serious security bug this year, although this has been fixed. But if you have a choice, prefer the default shell `sh` (usually this is Dash) for all server-side shell scripting. – Rick-777 Dec 13 '15 at 11:24
  • 1
    This worked for me but instead of using the complete /bin/bash path I just used sh as below exec.Command("sh", "-c", "command -v foo") otherwise I was getting the exit error 26/27 for most of my excecutions. – joe mwirigi Apr 16 '19 at 13:04
1

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.

Chris Townsend
  • 3,042
  • 27
  • 31
  • 1
    uuidgen is not a shell built-in command. A built-in command are e.g. alias, source, read, printf etc. https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html#Bash-Builtins – lyderic Jun 07 '18 at 17:56