doudou2121
2017-05-10 11:05
采纳率: 50%
浏览 796
已采纳

在golang中使用os / exec在特定目录内执行命令

I want to run a command inside a particular directory.So here are 2 ways to do it.

command := exec.Command("echo *tar.gz | xargs -n1 tar zxf") 
command.Dir = pathFinal 
cmdErr := command.Run()

This is not working for me on the otherhand,

command := "cd "+pathFinal+"; "+"echo *tar.gz | xargs -n1 tar zxf" 
cmd := exec.Command("/bin/sh", "-c", command) 
cmdErr := command.Run()

This is working. I want to implement it the first way. I don't know why it is not working Second one throws an error

Failed to untar file: exec: "echo *tar.gz | xargs -n1 tar zxf": executable file not found in $PATH Am I missing something?

图片转代码服务由CSDN问答提供 功能建议

我想在特定目录中运行命令。因此,这里有2种方法。

  command:= exec.Command(“ echo * tar.gz | xargs -n1 tar zxf”)
command.Dir = pathFinal 
cmdErr:= command.Run()  
   
 
 

另一方面,这对我不起作用,

  command:=“ cd” + pathFinal +“  ;“ +” echo * tar.gz | xargs -n1 tar zxf“ 
cmd:= exec.Command(” / bin / sh“,” -c“,command)
cmdErr:= command.Run()
 <  / code>  
 
 

此功能正常。 我想以第一种方式实施它。 我不知道为什么它不起作用 第二个错误

无法解压缩文件:exec:“ echo * tar.gz | xargs -n1 tar zxf”:可执行文件 在$ PATH中找不到 我遗漏了什么吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douqu2481 2017-05-10 12:30
    已采纳

    The first argument to Command specifies the executable to run. To run a shell pipe expression, execute a shell:

    command := exec.Command("/bin/sh", "-c", "echo *tar.gz | xargs -n1 tar zxf") 
    command.Dir = pathFinal 
    cmdErr := command.Run()
    
    点赞 打赏 评论

相关推荐 更多相似问题