I'm confused about the evaluation of backticks in bash. I've seen code like this before which makes sense:
This stores the output of the
whoami command in the
RESULT variable and confirms that backticks evaluate to the output of the command within them. But I've also seen code like the following:
if `wget google.com -T 2 -t 1 -o /dev/null`; then echo "Internet ok" fi
This is testing for internet connectivity by trying to get the google homepage (with a
-t 1 for a single try, a
-T 2 for a 2 second timeout, and a redirection to
/dev/null since it doesn't actually want the output rather it just wants to see if it succeeds). The code reads as if the author was expecting that the backticks would evaluate to the exit code of the
wget command rather than the output.
But it actually works. It prints
Internet ok if it can connect to google.com and if I change the url to some nonsense url that doesn't exist, it doesn't satisfy the if statement and prints nothing. I don't understand why this works.
Independently running the
wget command with valid and invalid urls prints nothing in both cases and only differs by exit code.
My conclusion is that there is a special construct for
if followed by backticks that returns the exit code rather than the output. Am I wrong?