我试图运行这样的多个命令。

docker run image cd /path/to/somewhere && python a.py

但是这给了我“没有这样的文件或目录”错误,因为它被解释为…

"docker run image cd /path/to/somewhere" && "python a.py"

似乎需要一些像“”或()这样的转义字符。

所以我也尝试了

docker run image "cd /path/to/somewhere && python a.py"
docker run image (cd /path/to/somewhere && python a.py)

但这些都没用。

我已经搜索了Docker运行参考,但没有找到任何关于转义字符的提示。


当前回答

对于其他想用docker-compose来做同样事情的人来说,你只需要在bash -c前加上引号,然后用&&把多个命令括起来。

因此,在OPs示例中,docker-compose run image bash -c "cd /path/to/somewhere && python a.py"

其他回答

如果您想将结果存储在容器之外的一个文件中,也就是在您的本地机器上,您可以这样做。

RES_FILE=$(readlink -f /tmp/result.txt)

docker run --rm -v ${RES_FILE}:/result.txt img bash -c "grep root /etc/passwd > /result.txt"

命令的结果将在本地机器的/tmp/result.txt中可用。

对于其他想用docker-compose来做同样事情的人来说,你只需要在bash -c前加上引号,然后用&&把多个命令括起来。

因此,在OPs示例中,docker-compose run image bash -c "cd /path/to/somewhere && python a.py"

你也可以在Docker容器中管道命令,bash -c "<command1> | <command2>"例如:

docker run img /bin/bash -c "ls -1 | wc -l"

但是,如果不调用远程shell,输出将被重定向到本地终端。

你可以通过以下几种方式做到这一点:

使用-w选项更改工作目录: -w,——workdir=""容器内的工作目录 https://docs.docker.com/engine/reference/commandline/run/#set-working-directory--w 将整个参数传递给/bin/bash: Docker运行镜像/bin/bash -c "cd /path/to/somewhere;python a.py”

如果你不介意在子shell中运行命令,只需在要运行的多个命令周围加上一组外括号:

docker run image (cd /path/to/somewhere && python a.py)