While working with bash programming, we many times need to check if a file already exists, create new files, insert data in files. Also sometimes we required executing other scripts from other scripts.
This article has few details about the test if file or directory exists in the system. Which can be very helpful for you while writing shell scripting.
#1. Test if 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 script creating 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 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 directory any other reason, we should make sure that 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.