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

In a bash script

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

Output: Yes

This means that “1” is considered as a true value.

But in the 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" echo "$word" | grep -q "$letter" echo "$word" | grep -q "$letter" echo "$word" | grep -q "$letter" will return 1, so why the result is No

How does the if keyword work to check the value returned by the command after if ?

+10
bash shell ubuntu
source share
3 answers

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

Can you display the return value of the last command executed with the $? variable $? :

 true echo $? # returned 0 false echo $? # returned 1 echo $? # returned 0 as the last executed command is 'echo', and not 'false' 
+13
source share

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 this command for true / false (ie, zero / non-zero value).

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

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

For your second example, this prints "No" because "nuxi" was not found in "Linux", if you change "nuxi" to "nux" (maybe it was a typo?) And remove the spaces around = then you get the expected behavior . eg.

 word=Linux letter=nux if echo "$word" | grep -q "$letter" then echo "Yes" else echo "No" fi 
+9
source share

This is because grep could not find the letter $ in $ word, so the exit code is 1. Whenever a process in linux returns a code other than 0, then this did not work. 0 means success. You can check it on echo "Linux" | grep -d "nuxi"; echo $? echo "Linux" | grep -d "nuxi"; echo $?

In the scripting world, on the other hand, 0 means false and 1 means true. So grep could not find the word and send 1 as the exit code in if, which took it as a true value.

0
source share

All Articles