Main Menu

search

You are here

Linux: Conditional/Loop Commands

[last updated: 2022-12-28]
Linux home page

Linux commands
-----

  • On this page:
    • if:
    • for:
    • while:
    • break:

    ---------------------------------------------

  • If:
    • if [ condition ]
      then
            statements
      else
            statements
      fi
    • Note: white space around the condition is required.
    • When condition compares numbers:
      if [ 45 -gt 40 ]
      if [ $num1 -lt $num2 ]
      Note: white space around arithmetic operator is required
        Operators available:
        -gt, -lt ... greater than, less than
        -eq, -ne ... equal, not equal
        -ge, -le ... greater than or equal, less than or equal
          you can also use the symbolic operators, <, >, <=, and >=
          however you must enclose them in double parentheses:
          if (($num1< $num2))
          Note: white space not needed anywhere
    • When condition compares strings:
      • if [ $str1 = $str2 ]
        -or- if [ $str1 == $str2 ]
        Note: white space required around variables and operator
      • However '==' acts differently inside double brackets:
        if [[ $str1 == z* ]] ... true if $str1 starts with the letter "z" .
        [Search online references to discover lots of complication using double brackets that is beyond my current understanding...]
      • if [ $str1 != $str2 ] ... not equal
      • if [[ $str1 < $str2 ]] ... less than ascii-alphabetically
        if [ $str1 \< $str2 ] ... must be escaped in single-brackets
  • Compound Conditions:
    • -a , && ... logical and
      if [ "$num1" -eq "$num2" ] && [ "$num1" -eq "$num3" ]
      if [ "$num1" -eq "$num2" ] && [ "$str1" = "$str2" ]
      if [ "$str1" = "$str2" -a "$num1" = "$num2" ]
    • -o, || ... logical or work similarly

---------------------------------

  • For:
    • for (( initializer; condition; step ))
      do
            commands
      done
    • for (( c=1; c<=5; c++ ))
      do
            echo "Welcome $c times"
      done
    • list all files in directory:
      for filename in *;
      do
            echo $filename
      done

    ---------------------------------

  • While:
    • while [ condition ]
      do
            command1
            command2
            command3
      done
    • while [ $someVar -gt 4 ]
      while [ $someVar -gt $otherVar ]
    • Same comparison operators for strings and numbers as listed for If statements above will work for while condition.

    ---------------------------------

  • Break statement:
    Use break whenever you want to force your program execution to leave a for- or while-loop before its end.
    You can also specify to break out of multiple loops using:
    break 2 ... for 2 loops for example

    ---------------------------------

    .

    .

    .

    eof