Reputation: 491
To run a bash terminal in a Docker container I can run the following:
$ docker exec -it <container> /bin/bash
However, I want to execute a command in the container automatically. For example, if I want to open a bash terminal in the container and create a file I would expect to run something like:
docker exec -it <container> /bin/bash -c "touch foo.txt"
However, this doesn't work... Is there a simple way to achieve this? Of course, I could type the command after opening the container, but I want to open a bash terminal and run a command at the same time.
Upvotes: 1
Views: 2429
Reputation: 26377
You can run your touch command and then spawn another shell :
docker exec -it <container> /bin/bash -c "touch foo.txt; exec bash"
Upvotes: 4
Reputation: 5517
Works perfectly fine for me
~# docker run -tid --rm --name test ubuntu:20.04
~# docker exec -it test /bin/bash -c "touch /foo.txt"
~# docker exec -it test /bin/bash
root@b6b0efbb13be:/# ls -ltr foo.txt
-rw-r--r-- 1 root root 0 Mar 7 05:35 foo.txt
Upvotes: 2
Reputation: 4115
When you run docker exec -it <container> /bin/bash -c "touch foo.txt"
, container sends 0 exit code
so that it means the task is done and you'll be returned to your host.
When you run docker exec -it <container /bin/bash
, bash
shell is not terminated until you explicitly type exit
or use CTRL+D
in bash environment. bash
is continuously running.
This is why when you run the second command, it goes to bash, runs your command (touches) and then exits.
Upvotes: 1
Reputation: 309
Easy solution:
docker exec -it <container> touch foo.txt
You can verify
docker exec -it <container> ls
This was tested with alpine
image.
Remember that in docker images there is a entrypoint
and a command
. Now we are editing the command of the default entrypoint for alpine
, via docker exec
It depends of the entrypoint if env variablers are load or not, $PATH
..., so other images maybe you need to write /bin/touch
or /usr/bin/ls
Good luck!
Upvotes: 1