Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a shell built-in command

Tags:

go

executable

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

like image 517
Konoha Avatar asked Dec 11 '15 17:12

Konoha


People also ask

How is a shell command executed?

The basic shell operation is as follows. The shell parses the command line and finds the program to execute. It passes any options and arguments to the program as part of a new process for the command such as ps above. While the process is running ps above the shell waits for the process to complete.

How do I execute a shell built-in command with AC function?

You should execute sh -c echo $PWD ; generally sh -c will execute shell commands. (In fact, system(foo) is defined as execl("sh", "sh", "-c", foo, NULL) and thus works for shell built-ins.) If you just want the value of PWD , use getenv , though.

What is a built-in command in shell?

In computing, a shell builtin is a command or a function, called from a shell, that is executed directly in the shell itself, instead of an external executable program which the shell would load and execute. Shell builtins work significantly faster than external programs, because there is no program loading overhead.


2 Answers

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")
like image 170
JimB Avatar answered Jan 03 '23 14:01

JimB


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.

like image 33
Chris Townsend Avatar answered Jan 03 '23 13:01

Chris Townsend