bash 在 shell 脚本中捕获失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16919317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:36:31  来源:igfitidea点击:

Catch failure in shell script

bashshellunix

提问by Mild Fuzz

Pretty new to shell scripting. I am trying to do the following:

shell 脚本编写非常新。我正在尝试执行以下操作:

#!/bin/bash

unzip myfile.zip

#do stuff if unzip successful

I know that I can just chain the commands together in with &&but there is quite a chunk, it would not be terribly maintainable.

我知道我可以将命令链接在一起,&&但是有相当多的块,它不会非常易于维护。

回答by

You can use the exit status of the command explicitly in the test:

您可以在测试中明确使用命令的退出状态:

if ! unzip myfile.zip &> /dev/null; then
    # handle error
fi

回答by fedorqui 'SO stop harming'

You can use $?. It returns:
- 0 if the command was successfully executed.
- !0 if the command was unsuccessful.

您可以使用$?. 它返回:
- 0 如果命令成功执行。
- !0 如果命令不成功。

So you can do

所以你可以做

#!/bin/bash

unzip myfile.zip

if [ "$?" -eq 0 ]; then
    #do stuff on unzip successful
fi

Test

测试

$ cat a
hello
$ echo $?
0
$ cat b
cat: b: No such file or directory
$ echo $?
1

回答by Mild Fuzz

The variable $?contains the exit status of the previous command. A successful exit status for (most) commands is (usually) 0, so just check for that...

该变量$?包含上一个命令的退出状态。(大多数)命令的成功退出状态是(通常)0,所以只需检查一下......

#!/bin/bash
unzip myfile.zip

if [ $? == 0 ]
then
    # Do something
fi

回答by Grzegorz ?ur

If you want the shell to check the result of the executed commands and stop interpretation when something returns non-zero value you can add set -ewhich means Exit immediately if a command exits with a non-zero status.I'm using this often in scripts.

如果您希望 shell 检查执行命令的结果并在某些返回非零值时停止解释,您可以添加set -e这意味着如果命令以非零状态退出,则立即退出。我经常在脚本中使用它。

#!/bin/sh

set -e

# here goes the rest