How to check if a path/file/dir exists or not in Linux bash shell script ?

Yesterday when i was creating a shell script, i want to input a path from user and make a check if the particular path exists or not.

Hence in this post, we will check a quick tip: how to check if an entered path is valid or not.

Checking if a path exists or not in a shell script

read path
### Here i an checking if the entered path is a file or directory.
if [ ! -e $path -o ! -d $path ]; then
### If there is no file or dir found with this path then it will execute this part.
echo "There is no directory or file named $path.";
echo "Please mention correct path or filename."
### exit from the program with return code 1
exit 1
fi

In the above program, we can understand the if condition as:

1. “-e $path” checks it the $path is a valid file.
2. “-o” is OR (return true if any of the above condition is true).
3. “-d $path” check if $path is a valid directory.
4. “!” reverse the result of the condition output and finally we have condition if file not exists and directory not exists.

It seems very small, however such small tips are very hard to identify.

Do post your comments/questions or suggestions below.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments