Home » Scripting and Automation » Bash / Shell Scripts » How to Check if File Exists using Bash Script ?

How to Check if File Exists using Bash Script ?

If we are processing certain file using bash shell script, its necessary to make sure the file exists in a directory before taking the action in script.

The below shell script can be used to check if the file is present or not in a specific directory

Open your favourite editor and create a script as below,

#!/bin/sh

#get the name of file to check if its present or not in pwd
FILE_TO_CHECK=$1

if [ ! -f $FILE_TO_CHECK ]
then
    echo "file $FILE_TO_CHECK does not exists"
else
    echo "file $FILE_TO_CHECK is present"
fi

Now, lets say you want to search myfile.pdf in a big list of files in a directory, then cd to that directory, copy this script there, and run the script as,

 $ bash script_to_check_file.sh myfile.pdf 

Here, if the file is present, above command will display below message in terminal,

file myfile.pdf is present

but if the file doesn’t exist, it will show as,

file myfile.pdf doesn't exists


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment