bash if

Basic flow of control statement.

&& and || are useful when test/result is simple.

But for more complex choices, the if statement exists.


basic if structures Simple if Simple if - else if - else if - else if - else if # Else not required An if statement can be expressed on a single line. Note that there is NOT a semi-colon between the then and the first action statement.
test command
  • if runs and tests results of command immediately following it.
  • Any command can be placed after the if
  • Don't need grave.
  • Can use && and || to create a multi-part test command sequence.
  • If a command generates output, remember to redirect.
  • ! - the bang preceding command will invert the return code. So command's failure is treated as true.
  • There must be at least one action statement. There may be many.
  • Use : to create a null action if needed.
  • Unix/Linux has special command, test that provide a number of useful tests. The result of these tests sets the return code that if checks.
    An if can have many elif statements. It may also contain other if statements in is action section. Use elif if tests are related, such as testing a file's type and permissions. Use an embedded if if the test are dissimilar. such as testing files existence and the number of lines in it.
    #!/bin/bash
    linecheck ()
    {
      if [ -f "$1" ]
      then
        #lc=`wc -l $1 | cut -d" " -f 1`
        #echo $lc
        if [ "`wc -l $1 | cut -d" " -f 1`" -gt 20 ]
        then
          echo "$1 has enough lines"
        else
          echo "$1 doesn't have enough lines"
        fi
      else
        echo "$1 does not exist"
      fi
    }
    

    linecheck file