Lesson 11.3: Making decisions: if, test and case
How if decides by exit status, the test command and its [ ] form (numbers -eq -gt -lt, strings = !=, files -f -d -e, -z for empty), why the spaces inside [ ] matter, if/elif/else in a disk-usage checker fed with real df output, && and || as short decisions, bash's [[ ]] with wildcards, and case for choosing between commands like start and stop. You add a new case to a service script in nano.
19 min
You will learn to
- Explain that if tests an exit status
- Compare numbers, strings and files with test and [ ]
- Write if/elif/else
- Use && and || for one-line decisions
- Match patterns with [[ ]]
- Choose between actions with case
Key terms
- Condition
- In bash, any command: if it exits with 0 the condition is true, otherwise false.
- test / [ ]
- The command that checks numbers, strings and files and answers with its exit status. [ … ] is the same command with a closing bracket.
- if / elif / else / fi
- Runs the block of the first true condition; else runs when none is true; fi closes it.
- [[ ]]
- bash's own test: no word splitting inside, == and != accept wildcards, =~ matches a regular expression (section 10), && and || work inside.
- case / esac
- Compares one value with patterns in order and runs the first matching branch; *) catches everything else; each branch ends with ;;.
- exit
- Ends the script and sets its exit status: exit 0 success, exit 1 (or other numbers) failure.
← Variables, arguments and input · All lessons · Loops: for, while and until →