Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux Go:将字符串与exec.Command一起使用时出现奇怪的结果_Linux_String_Go_Exec - Fatal编程技术网

Linux Go:将字符串与exec.Command一起使用时出现奇怪的结果

Linux Go:将字符串与exec.Command一起使用时出现奇怪的结果,linux,string,go,exec,Linux,String,Go,Exec,我有一个Go函数,用于处理Linux CLI命令及其参数: func cmd(cmd string, args ...string) ([]byte, error) { path, err := exec.Command("/usr/bin/which", cmd).Output() if err != nil { return []byte(""), err } response, err := exec.Command(string(path)

我有一个Go函数,用于处理Linux CLI命令及其参数:

func cmd(cmd string, args ...string) ([]byte, error) {
    path, err := exec.Command("/usr/bin/which", cmd).Output()
    if err != nil {
        return []byte(""), err
    }
    response, err := exec.Command(string(path), args...).Output()
    if err != nil {
        response = []byte("Unknown")
    }
    return response, err
}
它由以下函数调用:

func main() {
    uname, err := cmd("uname", "-a")
    fmt.Println(string(uname))
}
which命令返回二进制文件的正确路径,但当它尝试使用动态路径运行第二个exec命令时,返回的总是:

fork/exec /usr/bin/uname
: no such file or directory
exit status 1
但是,如果第二个exec命令是硬编码的,则一切都会按预期工作并打印uname:

response, err := exec.Command("/usr/bin/uname", args...).Output()
我是否遗漏了exec和字符串的行为

感谢

该命令在可执行文件的名称后打印一个换行符。path变量设置为/usr/bin/uname\n。没有具有此路径的可执行文件。额外的换行符在错误消息中可见。换行符正好位于:

修剪换行符后缀以获得可执行文件的正确名称:

 response, err := exec.Command(strings.TrimSuffix(string(path), "\n"), args...).Output()
which命令在可执行文件的名称后打印一个换行符。path变量设置为/usr/bin/uname\n。没有具有此路径的可执行文件。额外的换行符在错误消息中可见。换行符正好位于:

修剪换行符后缀以获得可执行文件的正确名称:

 response, err := exec.Command(strings.TrimSuffix(string(path), "\n"), args...).Output()

啊,非常感谢。由于换行,我没有注意到错误消息被分成两行。啊,非常感谢。由于换行,我没有注意到错误消息被拆分为两行。