英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论