Bash Tutorial · Bash Scripting · Lesson 17 of 30
Bash Conditionals: if, [[ ]] and case
Make decisions with if, test strings, numbers and files with [[ ]], and match patterns with case.
if and [[ ]]
if runs a command and checks its exit status (0 means true). [[ ... ]] is Bash's test command:
| Test | True when |
|---|---|
[[ $a == "$b" ]], != |
strings equal / differ |
[[ -z $s ]], [[ -n $s ]] |
string empty / not empty |
(( n > 5 )) or [[ $n -gt 5 ]] |
numeric comparison |
[[ -f path ]], -d, -e, -r, -x |
file exists / directory / exists / readable / executable |
[[ $s == *.log ]], [[ $s =~ ^[0-9]+$ ]] |
glob match / regex match |
Combine with &&, || and !.
touch config.yml
for f in config.yml missing.yml; do
if [[ -f $f ]]; then
echo "$f exists"
else
echo "$f is missing"
fi
done
input="42"
if [[ $input =~ ^[0-9]+$ ]] && (( input > 10 )); then
echo "$input is a number greater than 10"
fi
Output
config.yml exists missing.yml is missing 42 is a number greater than 10
Run this on your computer — see “Get Started” for setup.
case
case matches a value against patterns, which is cleaner than long if/elif chains:
for file in report.csv photo.JPG notes.txt archive.tar.gz; do
case "$file" in
*.csv) echo "$file: spreadsheet" ;;
*.jpg|*.JPG|*.png) echo "$file: image" ;;
*.tar.gz) echo "$file: archive" ;;
*) echo "$file: other" ;;
esac
done
Output
report.csv: spreadsheet photo.JPG: image notes.txt: other archive.tar.gz: archive
Run this on your computer — see “Get Started” for setup.
Test yourself
What does if check in Bash?
Whether the output is non-emptyThe exit status of the command (0 means true)Whether a variable is setA boolean variable
Show answer
Answer: The exit status of the command (0 means true)