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

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

Execute a command inside a particular directory using os/exec in golng

问题

我想在特定目录下运行一个命令。以下是两种方法:

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

这种方法可以工作。我想用第一种方法实现它,但不知道为什么它不起作用。第二种方法会抛出一个错误:

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

我是否漏掉了什么?

英文:

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?

答案1

得分: 2

第一个参数指定要运行的可执行文件。要运行一个 shell 管道表达式,执行一个 shell 命令:

command := exec.Command("/bin/sh", "-c", "echo *tar.gz | xargs -n1 tar zxf") 
command.Dir = pathFinal 
cmdErr := command.Run()
英文:

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

huangapple
  • 本文由 发表于 2017年5月10日 19:05:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/43890657.html
匿名

发表评论

匿名网友

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

确定