If you need to verify if a file or directory exists, you can use the test command. It will return true if there is a file or directory, and false otherwise. The test command can be used with any of the following parameters:
This article has few details about the test if a file or directory exists in the system. Which can be very helpful for you while writing shell scripting.
#1. Test if a file exists
If we required adding some content or need to create files from the script. First, make sure that the file already exists or not. For example one of my scripts creates logs in file /tmp/testfile.log and we need to make sure this file exists or not
1 2 3 4 5 6 | #!/bin/bash if [ -f /tmp/testfile.log ] then echo "File exists" fi |
The above statements can be also written using the test keyword as below
1 2 3 4 5 6 | #!/bin/bash if test -f /tmp/testfile.log then echo "File exists" fi |
Or in a single line we can write it as below. This is very useful while writing in shell scripting.
1 | [ -f /tmp/testfile.log ] && echo "File exists" |
to add else part in the above command
1 | [ -f /tmp/testfile.log ] && echo "File exists" || echo "File not exists" |
#2. Test if Directory Exists
Sometimes we need to create files inside a specific directory or need a directory for any other reason, we should make sure that the directory exists. For example we are checking /tmp/mydir exists for not.
1 2 3 4 5 6 | #!/bin/bash if [ -d /tmp/mydir ] then echo "Directory exists" fi |
The above statements can be also written using the test keyword as below
1 2 3 4 5 6 | #!/bin/bash if test -d /tmp/mydir then echo "Directory exists" fi |
Or in a single line we can write it as below
1 | [ -d /tmp/mydir ] && echo "Directory exists" |
#3. Create File/Directory if not Exists
This is the best practice to check file existence before creating them else you will get an error message. This is very helpful while creating shell scripts required to file or directory creation during runtime.
For File:
1 | [ ! -f /tmp/testfile.log ] && touch /tmp/testfile.log |
For Directory:
1 | [ ! -d /tmp/mydir ] && mkdir -p /tmp/mydir |
3 Comments
thank you Rahul
Thank you, Rahul!
Valuable tips for everyone, working with directories.
Hi
In my case I have multiple directories and have to check each directories if its not exist then create the directories.