如何执行一个shell内置命令

huangapple go评论96阅读模式
英文:

How to execute a shell built-in command

问题

我正在尝试找出Linux上是否存在一个程序,并找到了这篇文章。我尝试从我的Go程序中执行这个命令,但是它一直给我一个错误,说它在我的$PATH中找不到"command",这是可以预料的,因为它是Linux的内置命令,而不是一个可执行文件。所以我的问题是如何在Go程序中执行Linux的内置命令?

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

错误信息:exec: "command": 在$PATH中找不到可执行文件。

英文:

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

答案1

得分: 13

就像那篇文章所说的那样,“command”是一个内置的shell命令。你可以通过exec.LookPath在Go语言中原生地实现这个功能。

如果必要的话,你可以使用系统的which二进制文件,或者在shell中执行command命令,

exec.Command("/bin/bash", "-c", "command -v foo")
英文:

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

答案2

得分: 1

另外,如果是一个不需要参数的内置命令,你可以像下面这样做:

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

这将打印出一个类似于从命令行直接调用的唯一ID,例如:4cdb277e-3c25-48ef-a367-ba734ce407c1。

英文:

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.

huangapple
  • 本文由 发表于 2015年12月12日 01:45:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/34229486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定