Docker kill not working when executed in shell scr

2019-09-18 06:04发布

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?

1条回答
等我变得足够好
2楼-- · 2019-09-18 06:44

If you use set -e the script will exit when any command fails. i.e. when a commands return code != 0. This means if your start, exec or stop 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 the go test command as the overall return code.

#!/usr/bin/env bash

docker create -it --name test path
docker start test
docker exec test /bin/sh -c "go test ./..."
rc=$?
docker stop test
docker rm test
exit $rc

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 on EXIT, which means set -e can be used.

#!/usr/bin/env bash
set -e

# Set a default return code
RC=2

# Cleanup
function cleanup {
  echo "Removing container"
  docker stop test || true
  docker rm -f test || true
  exit $RC
}
trap cleanup EXIT

# Test steps
docker create -it --name test path
docker start test
docker exec test /bin/sh -c "go test ./..."
RC=$?
查看更多
登录 后发表回答