如何使用if语句检查退出状态 [英] How to check the exit status using an if statement

查看:179
本文介绍了如何使用if语句检查退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在if语句中检查退出状态以回显特定输出的最佳方法是什么.

I was wondering what would be the best way to check the exit status in an if statement in order to echo a specific output.

我在想是

if [ $? -eq 1 ]
then
   echo "blah blah blah"
fi

我还遇到的问题是,退出语句位于if语句之前,仅仅是因为它必须具有该退出代码.另外,我知道我做错了,因为退出显然会退出程序.

The issue I am also having is that the exit statement is before the if statement simply because it has to have that exit code. Also, I know I'm doing something wrong since the exit would obviously exit the program.

推荐答案

运行的每个命令都具有退出状态.

Every command that runs has an exit status.

该检查正在查看在该行运行之前最近完成的命令的退出状态.

That check is looking at the exit status of the command that finished most recently before that line runs.

如果您希望当测试返回true(上一条命令失败)时退出您的脚本,则可以将exit 1(或其他内容)放在echo之后的if块中.

If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.

话虽如此,如果您正在运行命令并希望使用以下命令测试其输出,通常会更直接.

That being said if you are running the command and wanting to test its output using the following is often more straight-forward.

if some_command; then
    echo command returned true
else
    echo command returned some error
fi

或者通过使用!进行求反来解决这个问题

Or to turn that around use ! for negation

if ! some_command; then
    echo command returned some error
else
    echo command returned true
fi

请注意,尽管这些都不关心错误代码是什么.如果知道只关心特定的错误代码,则需要手动检查$?.

Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.

这篇关于如何使用if语句检查退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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