douyi1197 2014-09-10 00:54
浏览 65
已采纳

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

I have a Go function that processes Linux CLI commands and their arguments:

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
}

Which is called by the following:

func main() {
    uname, err := cmd("uname", "-a")
    fmt.Println(string(uname))
}

The "which" command returns the correct path to the binary but when it tries to run the second exec command with a dynamic path the return is always:

fork/exec /usr/bin/uname
: no such file or directory
exit status 1

Yet if the second exec command is hardcoded, everything works as expected and prints the uname:

response, err := exec.Command("/usr/bin/uname", args...).Output()

Am I missing something about how exec and strings behave?

Thanks

  • 写回答

1条回答 默认 最新

  • drf97973 2014-09-10 01:04
    关注

    The which command prints a newline following the name of the executable. The path variable is set to "/usr/bin/uname ". There is no executable with this path. The extra newline is visible in the error message (the newline just before the ":").

    Trim the newline suffix to get the correct name of the executable:

     response, err := exec.Command(strings.TrimSuffix(string(path), "
    "), args...).Output()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)