In this tutorial, you will learn how to check file exists, directory exists using file test operators with shell scripting tutorial in linux / unix.
Three Operations
- Checking File / Directory exists using option -e
- Checking File exists using option -f
- Checking Directory exists using option -d
1. Checking File / Directory Exists or Not
- Here file / directory will be checked or not using the special option -e
- It will return success if the file /directory exists else it will return false.
Example – File / Directory Exists or Not
(op.sh)
SOURCE CODE
echo “Enter the file or directory : “
read fn
if [ -e $fn ]
then
echo “File / Directory exists…”
else
echo “File / Directory does not exist…”
fi
OUTPUT
2. Checking File Exists or Not
- Here file will be checked or not using the special option -f
- It will return success if file exists else it will return false
Example – File Exists or Not
(op.sh)
SOURCE CODE
echo “Enter the file name: “
read fn
# checking file exists or not using option -f
if [ -f $fn ]
then
echo “File exists…”
echo “Contents of File: “
echo “————————————“
cat $fn
else
echo “File does not exist…”
fi
OUTPUT
3. Checking Directory Exists or Not
- Here directory will be checked or not using the special option -d
- It will return success if file exists else it will return false
Example – Directory Exists or Not
(op.sh)
SOURCE CODE
echo “Enter the directory: “
read fn
# checking directory exists or not using option -d
if [ -d $fn ]
then
echo “Directory exists…”
echo “Contents of Directory: “
echo “————————————“
# cat $fn
ls $fn
else
echo “Directory does not exist…”
fi
OUTPUT