Bash: test commands in if, until and while

Time:2021-8-2

exit status

The status value returned when exiting after the execution of the previous command.

0Indicates success;Not 0Indicates a failure.

You can print and view the last status value on the command line

$ echo $?

If, until and while that depend on exit status

  • Syntax of until:

    until test-commands; do
      consequent-commands; 
    done
  • Syntax of while

    while test-commands; do
      consequent-commands; 
    done
  • If syntax

    if test-commands; then
      consequent-commands;
    [elif more-test-commands; then
      more-consequents;]
    [else alternate-consequents;]
    fi

test-commandsAfter execution,ifuntilwhileDepending on itsexit status

  1. When it is 0, if executes;
  2. When it is 1, until is executed;
  3. When is 0, while executes.

Test commands contains

One or more groups of pipes form test commands

  1. Multiple groups of pipes can be connected by;, &, &&, or||separate,
  2. from;, &, orLine feedend;
  3. exit statusBy the last set of pipesexit statusdecision;
  4. One or more commands form a pipeline, which consists of|or|&Separated by the of the last commandexit statusDetermine the of the pipelineexit status
  5. Generally speaking, a single command is executed successfully with a status value of 0.

    //File test
    #!/usr/bin/bash
    if ls;ls;then
      echo ==111==
    else
      echo ==222==
    fi
    
    if ls;lss;then
      echo ==333==
    else
      echo ==444==
    fi
    
    $ ./test
    test  test_1  test1
    test  test_1  test1
    ==111==
    test  test_1  test1
    ./test: line 8: lss: command not found
    ==444==

((arithmetic expression)) to form test commands

withlet "expression"

Add, subtract, multiply, divide, etc. the calculated value is 0,exit statusThe value is 1; The calculated value is non-zero,exit statusThe value is 0;

//File test
#!/usr/bin/bash
if ((1+1));then
  echo ==111==
else
  echo ==222==
fi

if ((1-1));then
  echo ==333==
else
  echo ==444==
fi

$ ./test
==111==
==444==

[[conditional expression]] forms test commands

//File test
#!/usr/bin/bash
if [[ str1 == str* ]];then
  echo ==111==
else
  echo ==222==
fi

if [[ 'str1' = 'str2' ]];then
  echo ==333==
else
  echo ==444==
fi

$ ./test
==111==
==444==

[conditional expression] forms test commands

withTest expression, similar[[conditional expression]]

//File test
#!/usr/bin/bash
if [ str1 == str* ];then
  echo ==111==
else
  echo ==222==
fi

if [ 'str1' = 'str2' ];then
  echo ==333==
else
  echo ==444==
fi

$ ./test
==222==
==444==

The difference between [[]] and []

  1. stay[[]]In, word segmentation and file name extension will not be performed.
  2. stay[[]]In,==and!=The operand on the right is treated as a regular expression(=Equivalent to==

reference resources