bash - bash脚本中比较运算符设置的退出状态

标签 bash exit status setting

以下 bash 脚本打印“错误!”而不是“服务器错误响应”,即使 wget 返回 8:

#!/bin/bash

wget -q "www.google.com/unknown.html"
if [ $? -eq 0 ]
then
    echo "Fetch successful!"
elif [ $? -eq 8 ]
then
    echo "Server error response"
else
    echo "ERROR!"
fi

当上面的脚本使用 -x 运行时,第一次与 0 的比较似乎是将退出状态设置为 1:

+ wget www.google.com/unknown.html
+ '[' 8 -eq 0 ']'
+ '[' 1 -eq 8 ']'
+ echo 'ERROR!'
ERROR!

我通过使用一个变量来存储 wget 退出状态来解决这个问题,但是我找不到 $? 的各种方式的任何引用。已设置。 bash 详细信息:

$ bash --version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

有人能给我指点一下吗?

最佳答案

$?man bash特殊参数参数部分中进行了非常简单的解释:

   ?      Expands to the exit status of the most recently  executed  fore-
          ground pipeline.

@chepner在他的评论中说得最好:

The key thing to understand is that each [ ... ] is a separate foreground pipeline, not part of the if statement's syntax, and they are executed in order, updating $? as you go along.

如果您想使用 if-else 链,请将 $? 的值保存在变量中,并在该变量上使用条件:

wget -q "www.google.com/unknown.html"
x=$?
if [ $x -eq 0 ]
then
    echo "Fetch successful!"
elif [ $x -eq 8 ]
then
    echo "Server error response"
else
    echo "ERROR!"
fi

但在这个例子中,案例会更实用:

wget -q "www.google.com/unknown.html"
case $? in
    0)
        echo "Fetch successful!" ;;
    8)
        echo "Server error response" ;;
    *)
        echo "ERROR!"
esac

关于bash - bash脚本中比较运算符设置的退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40597774/

相关文章:

bash - 如何使用 shell 脚本有效地处理大型 csv 文件,以获得比以下脚本更好的性能?

linux - 如何将查找输出重定向到文件中?

linux - 错误处理 Bash 脚本

php - PHP中的die()和exit()有什么区别?

bash - fish shell : Weird exit command behaviour from terminal

Java:如何检查打印机状态

Bash:在文件中弹出行

c - 退出 pthread 会导致段错误

java - Zebra GK420d ZPL 打印机通过 USB 在 Java 中的状态

wordpress - 在特定时间过后自动更改 WooCommerce 订单状态?