Since the contents of variables will, well, vary it is often useful to be able to make decisions based on them. Strings and numbers can be easily compared to explicit values or other variables. Here is a simple example:
$ i=107
$ if [ $i -gt 100 ]
> then
> echo "Wow, i got all the way up to $i"
> else
> echo "i is only up to $i"
> fi
Wow, i got all the way up to 107
$ i=22
$ if [ $i -gt 100 ]
> then
> echo "Wow, i got all the way up to $i"
> else
> echo "i is only up to $i"
> fi
i is only up to 22
Here we see a simple if
statement. When executed the expression within the brackets is evaluated to either true or false. If the expression is found to be true the commands after the then will be executed, otherwise the commands after the else are executed.
The expression shown here is the greater than expression (>
). The symbols we typically use for greater than and less than have specific significance in the UNIX shell, so to compare values we use -gt
for greater than and -lt
for less than. Comparisons can also be made between strings of text. More information about comparing text and numbers can be found in my book.
