英文:
How to pass a command with $() to exec.command() in golang
问题
我想在使用exec.command()
的Golang脚本中执行像docker exec "$(docker-compose ps -q web)" start.sh
这样的命令。问题是如何执行$()
内部的命令。
英文:
I want to execute a command like docker exec "$(docker-compose ps -q web)" start.sh
from golang script using exec.command()
. The problem is getting the command inside $()
to execute.
答案1
得分: 4
$()
内的命令会在命令行上由你的shell(通常是bash
,但也可以是sh
或其他)执行并替换为其输出。而exec.Command
直接运行程序,所以这种替换不会发生。这意味着你需要将该命令传递给bash,以便它解释和执行该命令:
bash -c "docker exec \"$(docker-compose ps -q web)\" start.sh"
代码示例:
exec.Command("/bin/sh", "-c", "docker exec \"$(docker-compose ps -q web)\" start.sh")
或者,你可以自己运行docker-compose ps -q web
,获取其输出并进行替换,而不是让bash为你执行替换。
英文:
The command inside of $()
is executed and replaced with its output by your shell on the command line (typically bash
but can be sh
or others). exec.Command is running the program directly, so that replacement isn't happening. This means you need to pass that command into bash so it will interpret and execute the command:
bash -c "docker exec \"$(docker-compose ps -q web)\" start.sh"
Code Example:
exec.Command("/bin/sh", "-c", "docker exec \"$(docker-compose ps -q web)\" start.sh")
Alternatively, you can run docker-compose ps -q web
yourself, get its output and do the substitution instead of having bash do it for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论