← Lessons/Conditionals & Tests
← Conditionals & Tests

Branch on a file

Learn

The if statement

The shape is always the same: test something, and run a block only when the test holds.

if [ -d logs ]; then
  echo "logs directory found"
fi

Read it like a sentence: if the directory exists, then print. fi is just if spelled backwards, Bash's way of closing the block.

Here's the part that surprises people: [ is a command, a synonym for test. It checks the condition you hand it and succeeds or fails, and if runs the block when it succeeds. That's also why the spaces matter: [ -d logs ] is the command [ with arguments, so it needs spaces around the brackets like any other command.

The tests you'll reach for constantly:

  • -f FILE: a regular file exists. -d DIR: a directory exists.
  • -z "$x": the string is empty. -n "$x": it's non-empty.
  • "$a" = "$b": the two strings are equal.

Print exactly config present only when config.yaml exists, using if [ -f ... ].

$ bash solution.sh
Loading...

Output

Run your solution to see its output here.