Scripts: tests and conditions
if, elif, else and fi, the test command and its [ ] form, file, string and number tests, the &&, || and ! operators, and case: choosing the branch a script runs and spotting a badly written test.
- 27 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
The test command: what is it?
Show the answer
A command that evaluates a condition without printing anything and answers through its exit code: 0 if it is true, 1 if it is false. It can also be written between brackets.
[is a real command: the spaces around the brackets are mandatory, and[-f x ]gives[-f: command not found.This script is launched with
./age.sh 18. What does it print?
```bash
age=$1
if [ "$age" -gt 18 ]; then
echo majeur
elif [ "$age" -ge 12 ]; then
echo ado
else
echo enfant
fi`adomajeurenfantadothenenfant
Show the answer
ado-gtis strict: 18 is not greater than 18, so the first branch is skipped.-ge 12is true, and only that branch runs.An
ifconstruct continues with … after the condition and ends with …; the optionalelsebranch goes before that last word.Show the answer
An
ifconstruct continues with then after the condition and ends with fi; the optionalelsebranch goes before that last word.fiisifspelled backwards, likeesacforcase.The if construct: what is it?
Show the answer
A statement that tries its conditions in order and runs only the first branch whose condition command returns code 0, or else its default branch if it has one.
The condition is not a boolean but any command:
if grep -q pattern f; thenworks with no brackets at all.The backup script must only continue if the file
$1exists and it was given exactly 2 arguments. Which test fits?[ -f "$1" ] || [ $# -eq 2 ][ -f "$1" ] && [ $# -ge 2 ][ -d "$1" ] && [ $# -eq 2 ][ -f "$1" ] && [ $# -eq 2 ]
Show the answer
[ -f "$1" ] && [ $# -eq 2 ]Two conditions to satisfy together are joined by
&&;||would accept one without the other.-fchecks the regular file (-dwould require a directory) and-eq 2asks for exactly two arguments, where-ge 2would accept three.