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

查看:23
本文介绍了如何使用 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(或其他)放入该 ifecho 之后的 块.

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

或者用!来否定

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天全站免登陆