How
linux
July 30, 20222 min read

How to check if a file exist in a Bash Script?

Data in Unix is organized into files. Several files are organized into directories. All directories are structured in a tree-like structure, called as the filesystem.

In Unix, most of the time, you end up working with files and perform operations on the same - like listing files, copying or moving files, deleting files etc.,

So, let's see jpw we can check if a file exists or not in a given path.

Check if a file exists in Bash Script

We use the if command to check if a file exists or not. if performs a conditional check on the command that goes inside the brackets [ ].

if [ -f "$FILE_PATH" ]; then
  # If the $FILE_PATH exist, code inside the block will get executed, for example:
  echo "File $FILE_PATH exist";
fi

Check if a file does not exists in Bash Script

Here we are checking the error condition or the negative condition if the file does not exist.

if [ ! -d "$FILE_PATH" ]; then
  # If the $FILE_PATH does not exist, code inside the block will get executed, for example:
  echo "File $FILE_PATH does not exist";
fi

Are you looking for the scenario if a directory exist or not in bash scripts?

There is also a shorthand notation to check if a file exist or not:

Shorthand to check if a file exist

[ -f "$FILE_PATH" ] && echo "File $FILE_PATH exist";

Shorthand to check if a file does not exist

[ ! -f "$FILE_PATH" ] && echo "File $FILE_PATH does not exist";

You can have any statement after the && symbol.

The above code is an ideal way to check if a file exists in a given path or not.

Share this blog
Tagged in :
linux
bash
Like what you read?
Subscribe to our Newsletter
Subscribe to our email newsletter and unlock access to members-only content and exclusive updates.
About the Author
Satvik
Satvik
Entrepreneur
Satvik is a passionate developer turned Entrepreneur. He is fascinated by JavaScript, Operating System, Deep Learning, AR/VR. He has published several research papers and applied for patents in the field as well. Satvik is a speaker in conferences, meetups talking about Artificial Intelligence, JavaScript and related subjects. His goal is to solve complex problems that people face with automation. Related projects can be seen at - [Projects](/projects)
View all articles