Patrik Mihalčin
Patrik Mihalčin

Reputation: 4061

How to execute commands in docker container as part of bash shell script

I would like to write a bash script that automates the following:

Get inside running container

docker exec -it CONTAINER_NAME /bin/bash

Execute some commands:

cat /dev/null > /usr/local/tomcat/logs/app.log
exit

The problematic part is when docker exec is executed. The new shell is created, but the other commands are not executed.

Is there a way to solve it?

Upvotes: 10

Views: 20869

Answers (2)

user2915097
user2915097

Reputation: 32216

You can simply launch

docker exec -it container_id cat /dev/null > /usr/local/tomcat/logs/app.log

Upvotes: -3

anubhava
anubhava

Reputation: 786146

You can use heredoc with docker exec command:

docker exec -i CONTAINER_NAME bash <<'EOF'
cat /dev/null > /usr/local/tomcat/logs/app.log
exit
EOF

To use variables:

logname='/usr/local/tomcat/logs/app.log'

then use as:

docker exec -i CONTAINER_NAME bash <<EOF
cat /dev/null > "$logname"
exit
EOF

Upvotes: 31

Related Questions