The Linux Command Line Chapter 27 Flow Control: Branching with if Prepared by Dr. Reyes, New York City College of Technology
Branching with if if – a statement that allows you to evaluate a condition and branch based on the results Syntax Example
Exit Status Exit Status – integer value returned by a command when it terminates execution Range from 0 - 255 Value of 0 indicates success Values 1 - 255 indicates error or failure Man pages explain what each exit status means for a command $? – parameter used to examine the exit status of the last command executed
Test and Expressions An if statement will test an expression You may use the keyword test or enclose the expression within brackets [ ] test expression [ expression ] When using [ expression ] you must leave a space after opening the first bracket and another space before closing the last bracket [expression] may give unexpected results (notice the lack of spaces) A test will return zero if the expression evaluates to true, non-zero otherwise. Strange, but to be consistent with the exit status explained before
String Expressions
String Script Example
Integer Expressions
Integer Script Example
Other Versions of test [[ expression ]] – allows the use of regular expressions and patterns, still need spaces. (( arithmetic expression )) – makes arithmetic tests easier, does not require spaces.
Combining Expressions Recommendation