大网数据广告活动
服务器运维问答

Docker exec/run shell command nesting

· 52CE 我爱测

A short introduction to the use case: I am using a docker container to run my go tests using go test ./... . This can be achieved easily using docker exec <container> /bin/sh -c "go test ./..." . Unfortunately go test ./... runs …

问题原文

原帖链接 · Wesley van Opdorp · CC BY-SA 3.0

A short introduction to the use case:

I am using a docker container to run my go tests using go test ./.... This can be achieved easily using docker exec <container> /bin/sh -c "go test ./...". Unfortunately go test ./... runs across all subdirectories and I'd like to exclude one (the vendor directory).

The advised solution for this is using the following command: go test $(go list ./... | grep -v '<excluded>', somehow this leaves me with the following result:

docker run golang:1.6.2-alpine /bin/sh -c "go test " (I have tested this on both run and exec, but they probably use the same core).

When I ssh into the container using docker exec -it <container_id> /bin/sh and run the exact same command, it works like a charm.

It seems that executing shell commands trough the docker exec/run does not support any commands nested with $()?

已采纳解答

原帖链接 · Will Barnwell · CC BY-SA 3.0

Your command may not be working as you expected thanks to a common bash gotcha:

docker exec <container> /bin/sh -c "go test $(go list ./... | grep -v '<excluded>')"

The command you are trying to run will perform the expansion of the subshell $() on your host because it is inside double quotes.

This can be solved by single quoting your command as suggested by @cuonglm in the question comments.

docker exec <container> /bin/sh -c 'go test $(go list ./... | grep -v "<excluded>")'

EDIT: A little demo

[wbarnwell@host ~]$ docker run -it --rm busybox /bin/sh -c '$(whoami)'
/bin/sh: root: not found
[wbarnwell@host ~]$ docker run -it --rm busybox /bin/sh -c "$(whoami)"
/bin/sh: wbarnwell: not found

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-06-09)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。