Linux 如果 [[ $? -ne 0 ]]; .ksh 中的意思

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20147964/
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-08-07 01:25:35  来源:igfitidea点击:

What does if [[ $? -ne 0 ]]; mean in .ksh

linuxbashunixksh

提问by Rahul sawant

I have a following piece of code that says if everything is executed mail a person if it fails mail the person with a error message.

我有以下一段代码,它说如果一切都执行了,如果失败,则向一个人发送邮件,并向该人发送错误消息。

if [[ $? -ne 0 ]]; then
  mailx -s" could not PreProcess files" [email protected]
else            
  mailx -s" PreProcessed files" [email protected]
fi
done

I am new to linux coding I want to understand what if [[ $? -ne 0 ]];means

我是 linux 编码的新手,我想了解这if [[ $? -ne 0 ]];意味着什么

采纳答案by bishop

Breaking it down, simple terms:

分解它,简单的术语:

[[ and ]]

... signifies a test is being made for truthiness.

... 表示正在对真实性进行测试。

$?

... is a variable holding the exit code of the last run command.

... 是保存上次运行命令的退出代码的变量。

-ne 0

... checks that the thing on the left ($?) is "not equal" to "zero". In UNIX, a command that exits with zero succeeded, while an exit with any other value (1, 2, 3... up to 255) is a failure.

... 检查左侧 ( $?) 的内容是否“不等于”为“零”。在 UNIX 中,以零退出的命令成功,而以任何其他值(1、2、3...最多 255)退出的命令是失败的。

回答by anubhava

if [[ $? -ne 0 ]]; 

Is checking return code of immediately previous this if condition.

正在检查此 if 条件之前的返回码。

  • $?means return code
  • $? -ne 0means previous command returned an error since 0 is considered success
  • $?表示返回码
  • $? -ne 0表示前一个命令返回错误,因为 0 被认为是成功

回答by Claudio

If the previous command returned an error return code.

如果前一个命令返回错误返回码。

回答by William Pursell

Presumably, the snippet is part of code that looks something like:

据推测,该片段是代码的一部分,如下所示:

 for var in list of words; do
   cmd $var
   if [[ $? -ne 0 ]]; then
      mailx -s" could not PreProcess files" [email protected]
    else            
      mailx -s" PreProcessed files" [email protected]
   fi
 done

Which could (and should) be re-written more simply as:

可以(并且应该)更简单地重写为:

for var in list of words; do
  if ! cmd $var; then
    message="could not PreProcess files"
  else
    message="PreProcessed files
  fi
  mailx -s" $message" [email protected]
done

The [[ $? -ne 0 ]]clause is a hackish way to check the return value of cmd, but it is almost always unnecessary to check $?explicitly. Code is nearly always cleaner if you let the shell do the check by invoking the command in the if clause.

[[ $? -ne 0 ]]子句是检查 的返回值的一种骇人听闻的方式cmd,但几乎总是没有必要$?显式检查。如果让 shell 通过调用 if 子句中的命令来进行检查,代码几乎总是更干净。