The following works fine when running the commands manually line by line in the terminal:
docker create -it --name test path
docker start test
docker exec test /bin/sh -c "go test ./..."
docker stop test
docker rm -test
But when I run it as a shell script, the Docker container is neither stopped nor removed.
#!/usr/bin/env bash
set -e
docker create -it --name test path
docker start test
docker exec test /bin/sh -c "go test ./..."
docker stop test
docker rm -test
How can I make it work from within a shell script?
If you use
set -e
the script will exit when any command fails. i.e. when a commands return code != 0. This means if yourstart
,exec
orstop
fails, you will be left with a container still there.You can remove the
set -e
but you probably still want to use the return code for thego test
command as the overall return code.Trap
Using
set -e
is actually quite useful and catches a lot of issues that are silently ignored in most scripts. A slightly more complex solution is to use a trap to run your clean up steps onEXIT
, which meansset -e
can be used.