kit.yang kit.yang - 4 years ago 110
Bash Question

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

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, why the result is No.

how the keyword
if
test the value returned by the command after
if
?

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download