🎓 A1Learner
🔍
0 of 50 lessons completed

Shell If Statements

An if statement is a way to run commands only when a check passes. It runs a command, and branches on whether that command succeeds.

Check that a file exists

-f is true when the name is a file.

if [ -f notes.txt ]; then
  echo "notes.txt exists"
fi

Check that a folder exists

-d is true when the name is a folder.

if [ -d docs ]; then
  echo "docs is a folder"
fi

Compare two strings

= is true when the strings match, and != when they differ.

name="Ana"
if [ "$name" = "Ana" ]; then
  echo "Hello, Ana"
fi
if [ "$name" != "Bo" ]; then
  echo "Not Bo"
fi

Check for an empty string

-z is true when the text is empty.

text=""
if [ -z "$text" ]; then
  echo "The text is empty"
fi

Branch with else

The else block runs when the check fails.

if [ -f missing.txt ]; then
  echo "Found it"
else
  echo "Not found"
fi

Branch on grep

If can branch on any command, not just a test.

if grep -q "milk" shopping.txt; then
  echo "Milk is on the list"
fi

Example

if [ -f report.txt ]; then
  echo "Report found"
  wc -l < report.txt
else
  echo "Report missing"
fi

Key points

  • If statement: if runs a command and runs its block only when the command succeeds.
  • Test command: test checks a condition, and [ ] is another way to write test.
  • File test -f: [ -f name ] is true when the name is a file.
  • Folder test -d: [ -d name ] is true when the name is a folder.
  • Empty test -z: [ -z "$text" ] is true when the text is empty.
  • String test: = checks that two strings match, and != checks that they differ.

In this example, the if statement tests report.txt with -f. The file exists, so the first block runs. Then wc -l counts its lines.

Note

Put quotes around a variable in a test, so an empty value still works.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does if [ -f notes.txt ] check?