• Arun Kumar

Shell Script to Check File or Directory

Linux shell script allows users to check and determine if the user input is a file or a directory. To achieve this we are using operators -f and -d.


vi check_file_directory.sh
# !/bin/bash
echo "Enter the file name: "
read file
if [ -f $file ]
then
echo $file "---> It is a ORDINARY FILE."
elif [ -d $file ]
then
echo $file "---> It is a DIRCTORY."
else
echo $file "---> It is something else."
fi

Here is the sample output of the above script

shell script to check file or directory

More ways to use -f and -d Operators

  • You can use it to check If a Directory Exists In a Shell Script [ -d "/path/to/dir" ] && echo "Directory /path/to/dir exists."

  • You can also check if File Exists test -f /etc/resolv.conf && echo "$FILE exists."


204 views

Recent Posts

See All