在shell脚本中执行时,Docker kill不工作 [英] Docker kill not working when executed in shell script

查看:787
本文介绍了在shell脚本中执行时,Docker kill不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在终端中逐行运行命令时,以下工作正常:

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

但是当我作为一个shell脚本运行时,Docker容器既不停止也不被删除。

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

如何使其在shell脚本中工作?

How can I make it work from within a shell script?

推荐答案

如果您使用 set -e ,则在任何命令失败时,脚本将退出。即当命令返回代码!= 0时,这意味着如果您的开始 exec 停止失败,您将留下一个集装箱。

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.

您可以删除 set -e ,但您可能仍然希望使用 go test 命令作为总体返回码。

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



陷阱



使用 set -e 实际上是非常有用的,并且捕获了许多在大多数脚本中被忽略的问题。一个稍微复杂的解决方案是使用陷阱 EXIT ,这意味着 set -e 可以使用。

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)
  (docker rm -f test)
  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=$?

这篇关于在shell脚本中执行时,Docker kill不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆