Linux: Check if a file or directory exists.

More often than you will need to verify in your scripts whether a file or directory exists or not. To do this, you can use the test…

Linux: Check if a file or directory exists.
Photo by Agence Olloweb on Unsplash

More often than you will need to verify in your scripts whether a file or directory exists or not. To do this, you can use the test command, let’s see how!

The test command has the following syntax

$ test <option> <filename>
  • option: The kind of check to perform
  • filename: the name of the file to verify

The option to verify if a file exists is -f if the file exists, the test command will exit with an exit code of 0 if not with 1

  • In this example, the command after && is executed if test exits with 0 and the command after || is executed if test exits with <> 0
$ test -f config.yml && echo "file exists" || echo "file does not exist" 
file exists

In a simpler form, you can verify the exit code by echoing the $? variable which holds the exit code of the last executed command.

$ test -f config.yml 
$ echo $? 
0 
$ test -f config.yml1 
$ echo $? 
1

You can negate the results by adding! before the option

$ test ! -f config.yml1 
$ echo $? 
0

To check if a directory exists you have to use the -d option

$ test -d ./scripts/ 
$ echo $? 
0

test can be used in your scripts like this

#!/bin/bash 
if test -f ./config.yml; 
then 
        echo "file exists" 
else 
        echo "file does not exist" 
fi

I hope you found this short article useful :)