我经常会遇到用/bin/bash -c或/bin/sh -c而不是直接执行的命令。例如,不是cp /tmp/file1 /tmp/file2,而是/bin/bash -c "cp /tmp/file1 /tmp/file2"。
这样做而不是直接执行命令的原因是什么?在最近的记忆中,我在Docker和K8s命令中看到的最多。我唯一能真正想到的是,因为您特别希望使用特定的shell运行命令,但这似乎是非常罕见的/小众的用例吗?
这里是一个特定的示例,k8s部署使用:
command: ["/bin/sh"]
args: ["-c", ". /config/dynamicenv.sh && /app/bin/docker-entrypoint server"]而不是我所期望的默认情况:
. /config/dynamicenv.sh && /app/bin/docker-entrypoint server发布于 2022-03-20 01:05:19
如果没有具体的示例,很难判断,但是这样做的一个常见原因是您希望使用shell i/o重定向、管道等等。例如,Kubernetes荚清单的这个片段将失败,因为它涉及一个管道,这需要shell执行命令行:
containers:
image: docker.io/alpine:latest
command:
- echo hello world | sed s/world/container/但这样做是可行的:
containers:
image: docker.io/alpine:latest
command:
- /bin/sh
- -c
- echo hello world | sed s/world/container/这是一种相对常见的情况,在这种情况下,您将看到一些事情使用shell显式执行。如果你想用一些具体的例子来更新你的问题,我们可以提供一个更彻底的答案。
你的例子非常接近我在回答中已经包含的内容。命令. /config/dynamicenv.sh && /app/bin/docker-entrypoint server不是一个简单的命令;它是一个同时使用.和&&运算符的shell脚本。
如果他们要写:
command: [". /config/dynamicenv.sh && /app/bin/docker-entrypoint server"]如果出现以下错误,它就会失败:
exec: "[\". /config/dynamicenv.sh && /app/bin/docker-entrypoint server\"]": stat [". /config/dynamicenv.sh && /app/bin/docker-entrypoint server"]: no such file or directory: unknown.为了正确执行命令,需要使用sh -c包装该命令。
https://stackoverflow.com/questions/71542693
复制相似问题