There are six types of control structures in bash: if/then, for, case, while, until, and select.
The if/then statement is much like the equivalent statement in other languages, and is used to test if a condition is true:
if [ condition ] then commands; elif [ condition ] then commands; else commands; fi
if [ condition ]; then literally means "If condition is true, then do what comes next." elif (the equivalent of else if) means "If not that but this...". Whatever comes after else is executed if none of the other conditions are true. fi (if spelled backwards) terminates the statement. Note that the elif and else sections are optional, but if, then, and fi are required.
The while loop repeats a series of commands for the period of time that a certain statement is true.
while [ condition ] do commands; done
The until loop is basically the opposite of a while loop. It repeats a series of commands as long as a condition is false.
until [ condition ] do commands; done
Example:
#!/bin/bash declare -i int=0; until [ $int -eq 10 ] do echo $int; int++; done
Outputs:
0 1 2 3 4 5 6 7 8 9
declare -i int initializes an integer variable int. -eq is the Shell notation for "equals" (for strings you use the = sign). ++ is the operator to increase an integer's value by 1.
The for loop is like the while loop, but rearranged. Instead of:
initialization; while condition do commands; increment; done
You have:
for((initialization; condition; increment)) do commands; done
This will be familiar to programmers with experience in languages like C, C++, and Java. Note, however, that this loop uses double parenthesis. This is to provide extra protection for the expressions inside.
The for loop can also loop through variables in a list, repeating an action for each list item. For instance:
#!/bin/bash for param in $* do echo $param; done
If this script is called like this:
$ source forscript "snake" "camel"
It will output:
snake camel
The case statement is similar to the switch-case statement of C-like languages, but with one major difference. Instead of testing the value of a variable, it tests to see whether a string matches a certain pattern. In Shell, these patterns are known as globs.
case $file in *.html ) echo "HTML file";; *.css ) echo "CSS stylesheet";; *.js ) echo "Javascript script";; * echo "Another type of file";; esac
Here, *.html, *.css, etc. are the globs. The * means any string of characters, so *.html would match either browser-stats.html or OS-stats.html.
The last flow control statement is the select statement, which creates a menu of items in a list.
#!/bin/bash select file in * do echo $file; break; done
This script will create a menu of files in the current directory. When the user selects one of the menu items, the name of the file will be output. break is necessary because it prevents the statement from looping indefinitely.