18

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?

kit.yang
  • 2,758
  • 3
  • 17
  • 17
  • You may find [my answer here](http://stackoverflow.com/questions/3869072/test-for-non-zero-length-string-in-bash-n-var-or-var/3870055#3870055) to be useful. – Dennis Williamson Oct 13 '10 at 14:38

3 Answers3

20

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'
Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
  • Ah,is it because '[' is a shell builtin ,it will return 0 when it complete the test function ? – kit.yang Oct 13 '10 at 13:39
  • It looks like `0` is an expression which evaluates to `true`. `[ 0 = 1 ]` has a return value of `1` (expected value) and `[ 0 = 0 ]` has a return value of `0`. Run `man test` for more information about `test` (a.k.a. `[`) – Lekensteyn Oct 13 '10 at 13:58
  • 7
    `[ 1 ]` or `[ 0 ]` evaluates to true because `test`/`[` with single parameter simply checks whether the parameter string (here `1` or `0`) is non-empty. iow `[ "" ]` would be false. – Dummy00001 Oct 13 '10 at 22:36
12

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
Nick
  • 7,700
  • 2
  • 29
  • 37
0

This is because the grep failed to find the $letter in $word, hence the exit code is 1. Whenever a process in linux return a code other than 0 then it means it failed. 0 means exited successfully. You can verify this by echo "Linux" | grep -d "nuxi"; echo $?

On the other hand in scripting world 0 means false and 1 mean true. So the grep failed to find the word and send 1 as an exit code to if, which took it as a true value.

Ibrahim
  • 1,247
  • 3
  • 13
  • 21