$? is explained, though very briefly, in the Special Parameters parameters section of
? Expands to the exit status of the most recently executed fore- ground pipeline.
@chepner put it best in his comment:
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 you want to use an if-else chain, then save the value of
$? in a variable, and use conditions on that variable:
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
But in this example, a
case would be more practical:
wget -q "www.google.com/unknown.html" case $? in 0) echo "Fetch successful!" ;; 8) echo "Server error response" ;; *) echo "ERROR!" esac