Check if File Exists in Bash Script

In this tutorial, you will learn how to use Bash scripts and if statements to check whether or not a file or directory exists.

Check if a File Exists

Use the -f operator to check if a file exists. This will only check ordinary files, and not directories.

#!/bin/bash
 
FILE="demo/test.txt"
 
if [ -f $FILE ];then
  echo "the file exists"
else
  echo "the file doesn't exist"
fi

Check if a File DOESN’T Exist

Use the ! operator to negate the file check. This tests to see if the file does NOT exist.

#!/bin/bash
 
FILE="demo/test.txt"
 
if [ ! -f $FILE ];then
  echo "file doesn't exist."
fi

Check if a Directory Exists

Use the -d operator to check if a directory exists.

#!/bin/bash
 
DIR="demo"
 
if [ -d $DIR ];then
  echo "the directory exists"
else
  echo "the directory doesn't exist"
fi

Check if a Directory DOESN’T Exist

Use the ! operator to negate the directory check. This tests to see if the directory does NOT exist.

#!/bin/bash
 
DIR="demo"
 
if [ ! -d $DIR ];then
  echo "the directory doesn't exist."
fi

Check If File OR Directory Exists

To check if a file OR directory exists, use the -e operator.

#!/bin/bash
 
PATH="demo/test"
 
if [ -e $PATH ];then
  echo "the file or directory exists"
else
  echo "the file or directory doesn't exist"
fi

Check if File OR Directory DOESN’T Exist

Use the ! operator to negate the file or directory check. This tests to see if the file or directory does NOT exist.

#!/bin/bash
 
PATH="demo/test"
 
if [ ! -e $PATH ];then
  echo "the file or directory exists"
else
  echo "the file or directory doesn't exist"
fi

Check Existence With Wildcard

The operators above don’t work well if you’re checking for the existence of a wildcard and expect to potentially have multiple matching results. The recommended approach would be to use the ls command.

In this example, we’ll check if a file with the .txt extension exists or not.

#!/bin/bash
 
if ls *.txt > /dev/null 2>&1 then 
    echo "the file exists"
fi

Create a File if It Doesn’t Exist

You can create a file if it doesn’t exist by using this script.

#!/bin/bash
 
FILE="test1.txt"
 
if [ ! -e $FILE ];then
  touch test1.txt
fi

Leave a Comment

Your email address will not be published. Required fields are marked *