Konoha
Konoha

Reputation: 337

How to execute a shell built-in command

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

Upvotes: 13

Views: 11858

Answers (2)

Chris Townsend
Chris Townsend

Reputation: 3162

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.

Upvotes: 1

Mr_Pink
Mr_Pink

Reputation: 109388

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

Upvotes: 14

Related Questions