如何在Golang中使用$()将命令传递给exec.command()函数?

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

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.

huangapple
  • 本文由 发表于 2016年2月4日 05:23:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/35187986.html
匿名

发表评论

匿名网友

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

确定