Linux Command Line · Lesson 38 of 43
Conditions and tests in Bash
Make scripts decide with if, elif, else and case: test files, strings and numbers with [ ] and [[ ]], and combine conditions with && and ||.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will make scripts decide: stop when a file is missing, pick an action depending on a value, and handle several cases cleanly. Conditions are the point where a script stops being a list and starts being a program.
if runs a command and checks its status
An if statement runs a command and looks at its exit status. Status 0 counts as true, and anything else as false. The classic form uses then and ends with fi (if backwards):
cd ~/project
if grep -q ERROR logs/app.log; then
echo "the log contains errors"
else
echo "the log is clean"
fithe log contains errorsgrep -q prints nothing and only reports through its exit status, which makes it ideal here. Any command works, including your own scripts.
The test command: [ ]
Most conditions use test, usually written as brackets. The spaces inside the brackets are required, because [ is really a command, and ] is its last argument:
if [ -f README.md ]; then echo "README.md is a file"; fi
if [ -d docs ]; then echo "docs is a directory"; fi
if [ ! -e missing.txt ]; then echo "missing.txt does not exist"; fiREADME.md is a file
docs is a directory
missing.txt does not existCommon file tests:
| Test | True when |
|---|---|
-e path |
it exists |
-f path |
it is a regular file |
-d path |
it is a directory |
-r, -w, -x path |
it is readable, writable, executable by you |
-s path |
it exists and is not empty |
-L path |
it is a symbolic link |
Put ! in front to negate a test.
Comparing strings
Use = and != for strings, and -z and -n to test for empty and non-empty. Always quote variables, so an empty value does not collapse the test:
name="Asha"
if [ "$name" = "Asha" ]; then echo "hello Asha"; fi
empty=""
if [ -z "$empty" ]; then echo "empty is empty"; fi
if [ -n "$name" ]; then echo "name is not empty"; fihello Asha
empty is empty
name is not emptyComparing numbers
Inside [ ], numbers use letter operators, because < and > would be read as redirections:
| Operator | Meaning |
|---|---|
-eq, -ne |
equal, not equal |
-lt, -le |
less than, at most |
-gt, -ge |
greater than, at least |
errors=$(grep -c ERROR logs/app.log)
if [ "$errors" -gt 1 ]; then
echo "$errors errors: investigate"
elif [ "$errors" -eq 1 ]; then
echo "one error"
else
echo "no errors"
fi2 errors: investigateelif adds further tests. With the double parentheses form (( errors > 1 )) you can write ordinary comparison operators, which many people find easier to read for arithmetic.
Bash's [[ ]] shortcut
Bash offers [[ ]], a more forgiving version. It does not split unquoted variables, supports && and || inside, and adds pattern and regular expression matching:
file="report-2026.csv"
if [[ $file == *.csv && $file == report* ]]; then echo "a report CSV"; fi
if [[ $file =~ ^report-([0-9]{4})\.csv$ ]]; then echo "year: ${BASH_REMATCH[1]}"; fia report CSV
year: 2026[[ ]] works only in Bash and similar shells, not in a plain sh, so use [ ] in scripts that must run everywhere. Inside [[ ]], a pattern on the right of == is not quoted, and =~ uses an extended regular expression.
Combining conditions: && and ||
&& runs the next command only if the previous succeeded, and || only if it failed. They give you short one-line conditions, and they make a common pattern:
mkdir -p out && echo "folder ready"
[ -f missing.txt ] || echo "missing.txt not found"
[ -d docs ] && [ -f docs/notes.txt ] && echo "notes found"folder ready
missing.txt not found
notes foundA word of care with cmd1 && cmd2 || cmd3: it is not an if/else, because cmd3 also runs if cmd2 fails. For anything but simple cases, use a real if.
case: many alternatives
When one value can match several patterns, case is clearer than a chain of elif. Each branch ends with ;;, and *) is the catch-all:
cat > action.sh <<'SCRIPT'
#!/bin/bash
case "$1" in
start) echo "starting" ;;
stop) echo "stopping" ;;
restart) echo "stopping, then starting" ;;
-h|--help) echo "usage: $0 start|stop|restart" ;;
*) echo "unknown action: $1" >&2; exit 1 ;;
esac
SCRIPT
bash action.sh start
bash action.sh --help
bash action.sh jump
echo "status: $?"starting
usage: action.sh start|stop|restart
unknown action: jump
status: 1Patterns can use the same wildcards as file names, and | separates alternatives. The same shape appears in service scripts, which take start, stop and restart.
Common mistakes
Missing spaces in [ ]. [-f file] fails. Write [ -f file ].
Unquoted variables. [ $name = Asha ] breaks when $name is empty or has spaces. Quote it.
Using > or < for numbers inside [ ]. They are redirections. Use -gt and -lt, or (( )).
Using = for numbers. [ 05 = 5 ] is false because strings differ, while [ 05 -eq 5 ] is true.
Forgetting ;; in case branches. Every branch needs one.
Exercise
Write check.sh that takes a path and says whether it is a file, a directory or missing, and exits with status 1 when it is missing. Extend it to report "empty" for a file with no content. Then write a case statement that maps y, yes, n and no (any capitalisation, using patterns like [Yy]*) to messages.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.