check if file exists in shell script

How to Check if File Exists in Shell Script

Many times you may need to check if a file exists or not while processing a shell script. If you try to perform operations on a file that doesn’t exist, you will get an error. So it is advisable to always check if a file exists, before you work with it. In this article, we will learn how to check if file exists in shell script.


How to Check if File Exists in Shell Script

it is very easy to check if file exists in shell script. Let us say you want to check if a file /home/data/file.txt exists or not. Here is the code to do so.

file='/home/data/file.txt'
if [ -f $file ]; then
    #code to be run if file exists
fi

In the above code, we use -f operator to check if a file exists or not. Alternatively, you can also use an if-else block.

file='/home/data/file.txt'
if [ -f $file ]; then
    #code to be run if file exists
else
    #code to be run if file does not exist
fi

Similarly, you can check if a file does not exist by adding a negation operator ! before the -f operator above.

file='/home/data/file.txt'
if [ ! -f $file ]; then
    #code to be run if file does not exist
fi

In fact, there are many file-related operators, just like -f, you can use to work with files. Here are some of them

-b filename - Block special file
-c filename - Special character file
-d directoryname - Check for directory Existence
-e filename - Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename - Check for regular file existence not a directory
-G filename - Check if file exists and is owned by effective group ID
-G filename set-group-id - True if file exists and is set-group-id
-k filename - Sticky bit
-L filename - Symbolic link
-O filename - True if file exists and is owned by the effective user id
-r filename - Check if file is a readable
-S filename - Check if file is socket
-s filename - Check if file is nonzero size
-u filename - Check if file set-user-id bit is set
-w filename - Check if file is writable
-x filename - Check if file is executable

In this article, we have learnt how to check if a file exists or not in shell script.

Also read:

How to Check if Directory Exists in Shell Script
How to Check if Directory Exists in Python
How to Get Directory of Shell Script
How to Create Multiline String in Python
How to Disable SSH Password Authentication

Leave a Reply

Your email address will not be published. Required fields are marked *