Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the keyword “if” test if a value is true or false?

Tags:

bash

shell

ubuntu

In bash script

if [ 1 ]
then
   echo "Yes"
else
   echo "No"
fi

Output: Yes

It represents that '1' is treated as true value.

But in code:

word = Linux
letter = nuxi
if echo "$word" | grep -q "$letter"
then
    echo "Yes"
else
    echo "No"
fi

Output: No

But echo "$word" | grep -q "$letter" will return 1, so why is the result is No.

How does the keyword if test the value returned by the command after if?

like image 251
kit.yang Avatar asked Oct 13 '10 13:10

kit.yang


2 Answers

The return value of a command is checked. [ 1 ] has a return value of 0 (true). Any other return value (like 1) indicates an error.

You can display the return value of the last executed command using the $? variable:

true
echo $?
# returned 0
false
echo $?
# returned 1
echo $?
# returned 0 as the last executed command is 'echo', and not 'false'
like image 126
Lekensteyn Avatar answered Oct 03 '22 22:10

Lekensteyn


In unix land, 0 is true and 1 is false.

For your first example:

if [ 1 ]
then
   echo "Yes"
else
   echo "No"
fi

"If" checks the exit code of the given command for true/false (i.e. zero/non-zero).

The square brackets actually invoke the "test" command (see "man test" for more information) and give the exit code to if.

"test 1" (or indeed "test any_string") returns true (0) so "Yes" is output.

For your second example, this outputs "No" because "nuxi" isn't found in "Linux", if you change "nuxi" to "nux" (perhaps this was a typo?) and remove the spaces around the = then you will get the behaviour you expect. e.g.

word=Linux
letter=nux
if echo "$word" | grep -q "$letter"
then
    echo "Yes"
else
    echo "No"
fi
like image 26
Nick Avatar answered Oct 03 '22 20:10

Nick