Check If a File or Directory Exist using Bash. How?

Claudio Sabato
6 min readMar 19, 2020

In Bash scripts is very common to check if a file or a directory exist.

How do you check if a file or a directory exists using Bash?

In Linux everything is a file. You can use the test command followed by the operator -f to test if a file exists and if it’s a regular file. In the same way the test command followed by the operator -d allows to test if a file exists and if it’s a directory. The test command can also be represented with single square brackets [ ] or double square brackets [[ ]].

Now that you know how to check if a file or directory exist in a Linux system using Bash, let’s have a look at some practical examples.

For instance, you might want to check:

  • if a log file already exists and create it if it doesn’t…
  • if a directory required for the correct execution of your script exists…

And these are just two of hundreds of scenarios for which you might want to verify this.

So, how can you do it?

Let’s get started!

--

--

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.