Liu Guangxuan
Liu Guangxuan

Reputation: 109

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.

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?

Upvotes: 1

Views: 619

Answers (1)

larsks
larsks

Reputation: 311238

The problem is that you're not protecting your "here" document from local shell expansion. 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. The contents of here document are parsed for variable expansion and other shell features.

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.

Upvotes: 2

Related Questions