Linux bash have different file and directory related functions to create, delete, change and check existence. In this tutorial we will look how to check a file or directory if it exists.
Check File Existence
We will use bash test mechanism. Bash test mechanism have two formats where we can use followings.
- test -f FILENAME
- [ -f FILENAME]
Square brackets format is preferred in conditional usage like
switch . In this example we will check if file named
$ if [ -f myinput.py ]; then echo "File Exist"; fi
Check If File Not Exist
Another use case it checking existing and returning the reverse answer or NOT’ing the Boolean result. If the file exist this will return not in
if conditional. We will use
! which is used by programming languages for Boolean reversing. In this example if the file named “myfile” do not exist we will print message.
$ if [ ! -f myfile ]; then echo "File Do Not Exist"; fi
Check Existence with test Command
As we stated previous
test is the same with
[ -f FILE] . It just provides a bit different syntax. We will use
-f and file name. In this example we will check file named
myinput.py and print result with
$ test -f myinput.py
$ echo $?
As we can see the result is
which means successful or
Test If Directory Exists
We can also check given directory existence. We will use
-d flag in order to test. In this example we will check if the directory named
$ if [ -d backup ]; then echo "Directory Exists"; fi