1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@LiuGuangxuan It doesn't make a difference here, but I recommend to use the $(command) syntax over backquotes, see gnu.org/software/bash/manual/html_node/…
@hek2mgl ok,got it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.