Zia
Zia

Reputation: 277

Shell script to enter Docker container and execute command, and eventually exit

I want to write a shell script that enters into a running docker container, edits a specific file and then exits it.

My initial attempt was this -

  1. Create run.sh file.
  2. Paste the following commands into it

    docker exec -it container1 bash
    sed -i -e 's/false/true/g' /opt/data_dir/gs.xml
    exit
    
  3. Run the script -

    bash ./run.sh
    

However, once the script enters into the container1 it lands to the bash terminal of it. Seems like the whole script breaks as soon as I enter into the container, leaving parent container behind which contains the script.

Upvotes: 5

Views: 6537

Answers (2)

Raghuveer Addagada
Raghuveer Addagada

Reputation: 19

The issue is solved By using the below piece of code

myHostName="$(hostname)"
docker exec -i -e VAR=${myHostName} root_reverse-proxy_1 bash <<'EOF'
sed -i -e "s/ServerName .*/ServerName $VAR/" /etc/httpd/conf.d/vhosts.conf
echo -e "\n Updated /etc/httpd/conf.d/vhosts.conf $VAR \n"
exit

Upvotes: 2

vladmihaisima
vladmihaisima

Reputation: 2248

I think you are close. You can try something like:

docker exec container1 sed -i -e 's/false/true/g' /opt/data_dir/gs.xml

Explanations:

  • -it is for interactive session, so you don't need it here.
  • docker can execute any command (like sed). You don't have to run sed via bash

Upvotes: 1

Related Questions