>_ IzzyLab

Hands-on task

This task is step 5 of the course “Your first bash script”

if: does the file exist

easy~6 min

Write the script /root/check-file.sh. It takes a path as its first argument and prints exists if there's a regular file at that path, and missing if there's nothing there or it's a directory.

$ bash check-file.sh /etc/hostname
exists
$ bash check-file.sh /etc
missing
$ bash check-file.sh /no/such/file
missing

With no argument it prints missing too.

What you'll practise:
  • bash scripts
  • if
  • test
  • file tests

Topic breakdown

To make a script do different things in different cases, there's if:

if [ condition ]; then
    commands if the condition is true
else
    commands if it isn't
fi

[ … ] is a test command, so the spaces after [ and before ] are required: bash won't understand [-d /backup]. The else branch is optional, and fi closes the whole if.

There are ready-made tests for files:

  • -e path — something exists at the path (a file, a directory…);
  • -f path — it's a regular file;
  • -d path — it's a directory.

For example:

if [ -d "$1" ]; then
    echo "it's a directory"
fi

Put a variable inside [ ] in double quotes: if its value is empty or contains spaces, the test breaks without them.

What's checked

  1. /root/check-file.sh created
  2. An existing file gives exists
  3. A missing path gives missing
  4. A directory gives missing
  5. No argument gives missing

What it looks like