if/else & test
if runs commands only when a condition is true. In Bash a "condition" is simply a command: if it exits with status 0 (success), the condition is true. Tests like "is this file there?" or "is x greater than 5?" are themselves commands: test, [ ] and [[ ]].
The if statement
bash · try it yourself
score=72
if [ "$score" -ge 50 ]; then
echo "passed"
fi
if [ "$score" -ge 90 ]; then
echo "grade A"
elif [ "$score" -ge 70 ]; then
echo "grade B"
else
echo "grade C"
fipassed
grade B
Syntax rules: then follows the condition (after ; or a newline), elif and else are optional, and the block ends with fi (if backwards). The spaces inside [ and ] are required: [ is a command and ] its last argument.
Any command works as a condition
bash · try it yourself
printf 'ada\nlinus\n' > users.txt
if grep -q '^ada