以下 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/