linux - 变量赋值退出shell脚本

标签 linux bash shell

我有一个简单的 shell 脚本,它试图找出特定的 docker 容器是否正在运行。在 shell 脚本中我有以下行;

RUNNING_CONTAINERS=$(docker ps -a | grep ${IMAGE_NAME})

如果 grep 没有返回结果,shell 脚本将立即退出。我该如何编写脚本以确保即使 grep 结果为空脚本也能继续执行?

最佳答案

其原因是代码中某处存在set -e,这使得您的脚本在命令返回非零状态时立即退出。在本例中,grep 因为它没有找到任何匹配项。

The Bash reference manual -> The set builtin 中所读

-e

Exit immediately if a pipeline (see Pipelines), which may consist of a single simple command (see Simple Commands), a list (see Lists), or a compound command (see Compound Commands) returns a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command’s return status is being inverted with !. If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit. A trap on ERR, if set, is executed before the shell exits.

此外,来自 man grep:

EXIT STATUS

Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred.

因此 grep 找不到任何内容并返回非零退出状态。然后,set -e 捕获它并发现它不是来自“异常”(ifwhile... 如引用),它也不是在管道中的最后一个命令之前,因此它退出。

测试

让我们创建一个非常基本的脚本:

$ cat a.sh 
#!/bin/bash

set -e
echo "hello"
grep "hello" a
echo "bye"

并生成一个空的a文件:

$ touch a

如果我们运行它,我们会看到它在 grep 没有返回任何结果时退出:

$ ./a.sh 
hello

但是,如果我们删除 set -e 行,它将一直到文件末尾:

$ ./a.sh 
hello
bye

另请注意,如果 grep 不是管道中的最后一个元素,它也不会失败:

$ cat a.sh
#!/bin/bash

set -e
echo "hello"
grep "hello" a | echo "he"
echo "bye"
$ ./a.sh 
hello
he
bye

关于linux - 变量赋值退出shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33693751/

相关文章:

linux - 如何将 git 从一台服务器备份到另一台服务器

shell - 将尾随零添加到整数

c++ - OpenCV:在哪里可以找到 CV_WINDOW_AUTOSIZE 常量?

linux - 在 bash 中按日期字段对日志进行排序

python - 如何在没有包的情况下在python中创建makefile

arrays - Bash shell 数组操作

C 编程给出\0 作为参数

php - 如何在 php 中使用 sudo 以 root 用户身份访问服务器

Java执行命令行程序 'find'返回错误

linux - Raspberry Pi 在启动时启动 xhost +