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

前端 未结 3 1452
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 06:33

In bash script

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

Output: Yes

It

3条回答
  •  花落未央
    2021-02-04 06:54

    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
    

提交回复
热议问题