Menu
CoddyTech

File Tests

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 7 of 39.

Before a script reads or writes a path, it can test what is there. Each test goes inside [[ ]] with the path after it:

  • -e: the path exists.
  • -f: it is a regular file.
  • -d: it is a folder.
  • -s: it exists and is bigger than zero bytes.
  • -r: you have permission to read it.

! in front flips a test, so [[ ! -f $1 ]] is true when $1 is not a regular file.

#!/bin/bash
if [[ ! -f $1 ]]; then
  echo "No such file: $1"
  exit 1
fi
if [[ -s $1 ]]; then
  echo "$1 has content"
else
  echo "$1 is empty"
fi

With todo.txt holding a line and log.txt empty, bash count.sh todo.txt prints todo.txt has content and bash count.sh log.txt prints log.txt is empty. A folder is not a regular file, so bash count.sh old prints No such file: old and exits with 1.

challenge icon

Challenge

Medium

Write a script that reports what a path is.

  1. Open what.sh. It takes one path as its first argument.
  2. Check the path in this order and print one line:
    • it does not exist: PATH: missing
    • it is a folder: PATH: folder
    • you cannot read it: PATH: not readable
    • it is an empty file: PATH: empty file
    • anything else: PATH: file with content
  3. Save the file.

Try it: run bash what.sh notes.txt, then bash what.sh photos. They print:

notes.txt: file with content
photos: folder

Then run bash what.sh old.txt, a path that does not exist: it prints old.txt: missing.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground