docker - Passing a complex shell script via docker exec sh -c "..."
问题描述
I have a script that works fine in sh
on a linux host as well as inside an alpine container. But when I try executing that using docker exec <containerID> sh -c "<script>"
it misbehaves. The script's function is to output stuff similar to ps.
systick=$(getconf CLK_TCK); for c in /proc/*/cmdline; do d=$(dirname $c); name=$(grep Name: $d/status); pid=$(basename $d); uid=$(grep Uid: $d/status); uid=$(echo ${uid#Uid:} | xargs); uid=${uid%% *}; user=$(grep :$uid:[0-9] /etc/passwd); user=${user%%:*}; cmdline=$(cat $c|xargs -0 echo); starttime=$(($(awk '{print $22}' $d/stat) / systick)); uptime=$(awk '{print int($1)}' /proc/uptime); elapsed=$(($uptime-$starttime)); echo $pid $user $elapsed $cmdline; done
EDIT: sh -c "<script>"
has the same behavior.
解决方案
You are not able to run this script from docker exec
because the variables will be interpolated before they sent to the container (i.e., you are going to get values from your local machine, not from within the container).
In order to run it as you wish, you need to replace $
with \$
for every occurrence of $
in your script.
What might work better is to put your script into a file, then map the file to a location within the container, using -v
(i.e., -v script.sh:/path/to/script.sh
), and call the script via docker exec /path/to/script.sh
推荐阅读
- javascript - 仅从数组中的每个对象中提取某些属性,并添加到新数组中
- bash - 在bash linux中要求用户输入日期“而”他没有输入日期
- java - 预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径处为 BEGIN_OBJECT,尽管 JSON 正确
- javascript - 需要帮忙。我删除了数据库中的 MongoDB 文档,但我的应用程序继续使用 AJAX 显示它们
- javascript - es6过滤并找到相同的对象
- android - 无法将我自己的 SMS 应用程序设置为默认值。任何建议如何解决它?
- pysimplegui - 如何选择表格中的单元格?
- python - 如何从熊猫数据框制作PSD图?
- c - 我的 switch 语句没有从我的 for 循环中获取值
- python - txn.get("somekey") 是否占用了其余 python 脚本的 RAM?如果是,如何释放它使用的 RAM?