即使wget返回8,下面的bash脚本也打印"ERROR!"而不是"Server ERROR response":
#!/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在评论中说得最好:
要理解的关键是每个
[ ... ]
都是一个单独的前景管道,而不是if语句语法的一部分,并且它们按顺序执行,在您继续执行时更新$?
。
如果你想使用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
但是在这个例子中,case
会更实用:
wget -q "www.google.com/unknown.html"
case $? in
0)
echo "Fetch successful!" ;;
8)
echo "Server error response" ;;
*)
echo "ERROR!"
esac
尝试在$?或者存储$?