AI Hints
Home›Linux Tutorial›Decisions and Loops
Linux · Lesson 103 of 120

Making Decisions

If and test.

⏱ 2 min read▶ Video at 2:18:06🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

A useful script needs to make choices. If the file exists, read it. If not, warn the user. In bash, choices are made with if, and a test inside square brackets.

Making Decisions
From the video: Making Decisions
  • Scripts make choices
  • File exists? Read it
  • Otherwise, warn

check.sh

If, then a test in square brackets. Dash F asks, is this a normal file? If the test passes, bash runs the lines after then. Otherwise, it runs the lines after else. And FI, which is if backwards, ends the whole thing.

nano check.shbash
#!/bin/bash
file="$1"
if [ -f "$file" ]; then
  echo "$file exists. It has $(wc -l < "$file") lines."
else
  echo "Sorry, $file was not found."
fi

Both paths

Ask about notes dot TXT, and the test passes. It exists, with three lines. Ask about a file that isn't there, and the else part runs instead.

Terminal
./check.sh notes.txt
notes.txt exists. It has 3 lines.
./check.sh shopping.txt
Sorry, shopping.txt was not found.

Common tests

Here are the tests you'll use most. Dash F for a file, dash D for a folder, dash Z for an empty string. For numbers, use dash EQ for equal, dash GT for greater than, and dash LT for less than. And always keep a space inside each square bracket. Bash is fussy about that.

TestTrue when
[ -f path ]it's a file
[ -d path ]it's a folder
[ -z "$x" ]$x is empty
[ "$a" = "$b" ]the text matches
[ "$n" -gt 5 ]number greater than 5

Summary

If, a test in square brackets, then, else, and FI. Tests check files, text, and numbers. Next, more than two choices, with ELIF.

Key takeaways
  • if [ test ]; then … fi
  • -f -d -z
  • -eq -gt -lt
Next up: More Choices — elif and numbers