Bash, lesson 4
In most languages, if checks whether an expression is true. In Bash, if runs a command
and checks its exit status: 0 (success) takes the then branch, anything else does not. Bash
gives you special commands whose only job is to test things.
The block ends with fi ("if" backwards). The ; before then separates the test from the
keyword; you could also put then on the next line.
[[ ... ]] is Bash's test command. The spaces just inside the brackets are required:
[["$a" == "b"]] is an error.
2 exercises to try what you just read.
| Test | True when |
|---|---|
[[ $a == $b ]] | the strings are equal |
[[ $a != $b ]] | the strings differ |
[[ -z $a ]] | a is empty |
[[ -n $a ]] | a is not empty |
[[ $a == y* ]] | a matches the pattern (starts with y) |
Inside [[ ]], an unquoted right side of == is a pattern: * matches anything, ? one
character, and [abc] one of those characters. Quote it (== "y*") to compare literally. Also
note that < and > inside [[ ]] compare text alphabetically, not as numbers, which is a
classic bug.
You will also see the older single-bracket form [ ... ] (the test command) in scripts. It
works, but it needs more careful quoting. In Bash, prefer [[ ]].
For numbers, use arithmetic: (( )) succeeds when the expression is non-zero, so ordinary
comparison operators just work:
Inside (( )) you can use ==, !=, <, <=, >, >=, and no $ is needed. The older
style [[ $age -ge 18 ]], with -eq, -ne, -lt, -le, -gt and -ge, does the same thing.
Use && (and), || (or) and ! (not), inside a test or between commands:
&& and || between commands also work as a short if:
[[ -z $name ]] && name="guest" sets a default only when name is empty.
When you compare one value against many options, case is tidier than a chain of elif:
Each pattern ends with ), | separates alternatives, each branch ends with ;;, and *
catches everything else. The first matching branch runs, and the block ends with esac.
Read a temperature in °C (a whole number) and print the state of water at that temperature:
ice below 0,water from 0 up to 99,steam at 100 or above.Sample input:
Sample output:
Read a file name and print what kind of file it probably is, based on its ending:
.jpg, .jpeg or .png: image.mp3 or .wav: audio.txt or .md: textunknownIf the line is empty, print no file name. Matching is case-sensitive.
Sample input:
Sample output:
if [[ "$answer" == "yes" ]]; then
echo "Great!"
elif [[ "$answer" == "no" ]]; then
echo "Maybe next time."
else
echo "Please answer yes or no."
fiif (( age >= 18 )); then
echo "adult"
fiif [[ -n $name && $name != "root" ]]; then echo "ok"; fi
if (( n > 0 && n % 2 == 0 )); then echo "positive and even"; ficase "$day" in
Sat|Sun) echo "weekend" ;;
Mon|Tue|Wed|Thu|Fri) echo "weekday" ;;
*) echo "not a day" ;;
esac25waterholiday.pngimage