很多時候,我會遇到使用/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
uj5u.com熱心網友回復:
沒有具體的例子很難說,但這樣做的一個常見原因是你想使用 shell i/o 重定向、管道等。例如,Kubernetes pod manifest 的這個片段會失敗,因為它涉及管道,這需要 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不是一個簡單的命令;它是一個使用 the.和&&運算子的 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://www.uj5u.com/caozuo/447757.html
