shellstreak

Bash if statements: if, elif, else and test

Updated · Every command on this page ran in our practice shell

Short answer

Write if [ test ]; then commands; elif [ test ]; then commands; else commands; fi. Use -f to test for a file, -d for a folder, -z for an empty string, = to compare text and -lt, -gt or -eq to compare numbers. Keep the spaces inside the brackets and quote your variables.

An if statement runs a command and checks whether it succeeded. Most of the time that command is [ ], the test command, which checks things like does this file exist? or is this number less than 180?. The examples below ran in a practice shell, on a bakery's small collection of scripts.

The basic shape

if, then the test, then then, the commands, and fi to close. On one line, put ; before then and before fi. The spaces inside [ ] are required: [ -f menu.txt ], never [-f menu.txt].

example
learner@shellstreak:~/bakery$ if [ -f menu.txt ]; then echo "menu ready"; fi
menu ready

if, elif and else in a script

In a script, each part goes on its own line. elif adds another test, and else catches everything left over:

if [ -f "$1" ]; then
  echo "$1 is a file"
elif [ -d "$1" ]; then
  echo "$1 is a folder"
else
  echo "$1 not found"
fi
example
learner@shellstreak:~/bakery$ bash scripts/check-file.sh scripts; bash scripts/check-file.sh cakes.txt
scripts is a folder
cakes.txt not found

Script arguments: $1, "$@" and $#

Inside a script, $1, $2... are the arguments you typed after its name, "$@" is all of them (each kept whole, so use it with the quotes when you pass them on), "$*" is all of them joined into one string, and $# is how many there are. That's what most if tests in scripts look at. Quote an argument with spaces to keep it as one.

example
learner@shellstreak:~/bakery$ ./scripts/count-args.sh "rye bread" bagel
2 items: rye bread bagel

Test for files and folders

-f is true for a regular file, -d for a directory, -e for anything that exists, -x for something you can execute and -s for a file that isn't empty. ! flips a test: [ ! -d backups ].

example
learner@shellstreak:~/bakery$ [ -d backups ] || echo "no backups yet"
no backups yet

Test for empty strings with -z and -n

[ -z "$VAR" ] is true when the variable is empty or unset, and [ -n "$VAR" ] when it has a value. Always quote the variable: an unquoted empty variable disappears and the test breaks.

example
learner@shellstreak:~/bakery$ ORDER=""; if [ -z "$ORDER" ]; then echo "no order yet"; fi
no order yet

Compare text with = and !=

Inside [ ], = checks that two strings are the same and != that they differ. Quote both sides.

example
learner@shellstreak:~/bakery$ day=sunday; if [ "$day" = "sunday" ]; then echo closed; else echo open; fi
closed

Compare numbers with -lt, -gt and friends

Numbers have their own operators: -eq, -ne, -lt, -le, -gt and -ge, as in [ 150 -le 180 ]. Inside [ ], < and > are redirections, not comparisons, and inside [[ ]] they compare text, where 10 comes before 9.

example
learner@shellstreak:~/bakery$ temp=150; if [ "$temp" -lt 180 ]; then echo "too cold"; fi
too cold

Shortcuts with && and ||

[ ] is a command with an exit code, so you can skip if for one-liners: test && do-this, or test || do-that. Don't combine them as test && a || b: that isn't if/else, because b also runs when a fails (shellcheck's SC2015). Use a full if for two branches or more than one command.

example
learner@shellstreak:~/bakery$ [ 10 -gt 9 ] && echo number; [[ 10 < 9 ]] && echo text
number
text

Check yourself

One real exercise from the “Shell scripting” unit. No account needed.

Check whether scripts/greet.sh is a file, and if so print script found, using [ -f ] and &&.

What's checked: the output of your last command.

Common mistakes

  • Leaving out the spaces: [-f file] or [ $a=$b ]. Every part of a test is a separate word.

  • Comparing numbers with < or > inside [ ]. That redirects input or output to a file called after the number. Use -lt and -gt.

  • Not quoting variables. If $name is empty, [ $name = x ] becomes [ = x ] and bash complains unary operator expected.

  • Forgetting fi, or the ; before then on a one-line if.

Questions

What's the difference between [ ] and [[ ]]?+

`[ ]` is the portable `test` command and works in any POSIX shell. `[[ ]]` is a bash keyword: it doesn't split unquoted variables and supports patterns like `[[ $f == *.txt ]]`, but it's not available in plain `sh`.

How do I check if a file exists in bash?+

`if [ -f path ]; then ...; fi` checks for a regular file. Use `-d` for a directory or `-e` for anything at that path.

Should I use = or == in bash tests?+

Both work in bash, but `=` is the portable form inside `[ ]`. `==` is common inside `[[ ]]`.

Reading is step one. Now make it stick.

Practise this in a five-minute lesson with instant feedback. No account needed.

Practise it now