简体   繁体   English

如何进入docker容器使用shell脚本做点什么?

[英]How to enter docker container use shell script and do something?

I want to enter my container and do something, then leave this container.我想进入我的容器并做一些事情,然后离开这个容器。

#!/bin/bash
docker exec -i ubuntu-lgx bash << EOF

echo "test file" >> /inner.txt
ls -l /inner.txt
content=`cat /inner.txt`
echo ${conent}                                                             

# do something else

EOF

when I run this script, the bash tell me the file is not exist.but the ls can output the file's property.当我运行这个脚本时,bash 告诉我文件不存在。但是ls可以 output 文件的属性。

cat: /inner.txt: No such file or directory
-rw-r--r--. 1 root root 58 Nov 14 11:51 /inner.txt

where am I wrong?我哪里错了? and how to fix it?以及如何解决?

The problem is that you're not protecting your "here" document from local shell expansion.问题是您没有保护您的“此处”文档免受本地 shell 扩展的影响。 When you write:当你写:

#!/bin/bash
docker exec -i ubuntu-lgx bash << EOF

content=`cat /inner.txt`

EOF

That cat /inner.txt is run on your local system, not the remote system. cat /inner.txt在您的本地系统上运行,而不是在远程系统上运行。 The contents of here document are parsed for variable expansion and other shell features.解析此处文档的内容以进行变量扩展和其他 shell 功能。

To prevent that, write it like this:为了防止这种情况,请这样写:

#!/bin/bash
docker exec -i ubuntu-lgx bash << 'EOF'

echo "test file" >> /inner.txt
ls -l /inner.txt
content=`cat /inner.txt`
echo ${content}                                                             

# do something else

EOF

The single quotes in 'EOF' are a signal to the shell to interpret the here document verbatim. 'EOF'中的单引号是向 shell 逐字解释此处文档的信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 linux shell 脚本中做这样的事情 - How to do something like this in linux shell script 如何输入ubuntu docker容器的bash? - How to enter bash of an ubuntu docker container? Git安装脚本如何输入shell命令 - Git Install Script How to enter shell command shell脚本中是否有一种方法,如果[ <script exits with non-0 value> ] then; do <something> - Is there a way in the shell script that if [ <script exits with non-0 value> ] then; do <something> 在 Docker 容器中运行的 shell 脚本中的“退出”语句会退出脚本,也会退出容器; 我可以阻止退出容器吗? - The ‘exit' statement in a shell script running in a Docker container exits the script but also the container; Can I prevent exiting the container? docker在不退出容器的情况下在后台运行shell脚本 - docker run a shell script in the background without exiting the container 在容器内从 docker-compose 命令运行 shell 脚本 - Run a shell script from docker-compose command, inside the container 在linux脚本中访问在docker容器中运行的mongo shell - Access mongo shell running in docker container in linux script 如何以 tcsh 作为 shell 而不是 Bash 运行基于 linux 的 docker 容器? - How do I run the linux based docker container with tcsh as the shell instead of Bash? 如何在系统命令中使用awk脚本的shell变量? - How do I use shell variables of awk script in system command?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM