Skip to content

Take action based on the presence of a file

To control if the script should run based on if a certain file exists or not you can use the -e option in a if..else check.

the -e option simply stand for exist and will return a true or false value that is further processed by the if..else.

This is 2 ways of many you can do this, in the first example we check if the file exist and decide to do something both on if it returns True or False, in some scenarios this is desired but sometimes you just want to check if it do not exist and not execute anything special and just continue with rest of the script as in example 2 when it exists.

Example 1
# File to check for
eFile="test.txt"

# Do the check
if [ -e "$eFile" ]
then
  # When file exist, we can do some stuff as a
  # pre prep for the rest of the script.
  echo "File exist.."
else
  # When file do not exist we can do som stuff and then exit.
  echo "File do not exist"
  # This terminates the script returning error id 1
  exit 1
fi

# This row will only be executed if the file exist.
echo "Yeah i could print this..."
In example 2 we put a ! in front of -e this changes the check from exist to not exist and eliminated any special actions for exist, it will of course still execute the rest of the script in this case when the file exists.

Example 2
# File to check for
eFile="test.txt"

# Do the check
if [ !-e "$eFile" ]
then
  # When file do not exist.
  echo "File do not exist"
  # This terminates the script returning error id 1
  exit 1
fi

# This row will only be executed if the file exist.
echo "Yeah i could print this..."