top of page

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."


Related Posts

Heading 2

Add paragraph text. Click “Edit Text” to customize this theme across your site. You can update and reuse text themes.

bottom of page