top of page
Shell Script to Check File or Directory
Verify if a path is a file or directory with a shell script.
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](https://static.wixstatic.com/media/15aea5_8aae65dfc7a64a459fef6634607ca33c~mv2.png/v1/fill/w_66,h_35,al_c,q_85,usm_0.66_1.00_0.01,blur_2,enc_auto/15aea5_8aae65dfc7a64a459fef6634607ca33c~mv2.png)
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."
bottom of page