I'm confused about the evaluation of backticks in bash. I've seen code like this before which makes sense:
RESULT=`whoami`
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?
Best Answer
No, the backticks do not have a special meaning and you even could run the
wget
command without them in theif
statement.if
always evaluates the exit code of the command followed.A more comprehensive overview can be found here.
EDIT
Backticks initiate a command substitution which is executed in a subshell and returns an exit code.
if
just checks return codes, it does not make use of the output of the command.To compare the output of a command you could use the
[
, which must be closed with]
, which basically is a test. The test could be anythingman test
a string comparison
an integer test
If the test succeeds you get an exit code 0 ( true ), otherwise not 0 ( false ) which is again evaluated by
if
.So you have something in mind like follows.
But this wouldn't make much sense, due to redirecting the output to
/dev/null
you will always get true from[ "
wget google.com -T 2 -t 1 -o /dev/null" == "" ]
.On the other hand it also would not be useful to check if the output of the
wget
command does contain output, leaving out the-o /dev/null
, because even in an error situation you will get output, but different return codes.