Technofunction

Linux Shell Script to Determine whether a file exist or not

Shell script is a series of command’s written in a plain text file. It is somewhat similar to the batch-file in MS-DOS but have much more power and functionality than MS-DOS batch file. The major advantage is that you don’t need to write the same set of instructions again, since you can execute it via your script file.  It is majorly used to automate the tasks of day to day life and moreover can be used to automate the system administration part.

Below is an example of a script file by which you can determine whether a file exists or not. This script is used to tell you only whether file exists or not, but not its location as to where it is located. For that you can use FIND OR LOCATE command. We have created a file named existence-of-file.sh you may create a file with some other name. But it is convenient to save the file with ( .sh ) extension so that at later point of time you can recognize that it is a script file. Also in below code whatever is in front of # is a comment.

  • # vi existence-of-file.sh  <filename.sh>

#

# Determining whether a file exist or not, filename is supplied as an command line argument

#

if [ $# -ne 1 ]

then

echo “Usage – $0  file-name”

exit 1

fi

if [ -f $1 ]

then

echo “$1 file exist”

else

echo “Sorry, $1 file does not exist”

fi

#

Save and exit from vi ( wq! )

  • next you need to make this script file executable which can  be done by following command

# chmod +x existence-of-file.sh

# chmod 755 existence-of-file.sh

  • Now everytime you execute this script provide the filename and in the next line it will determine whether a file exist or not.

# ./ existence-of-file.sh <filename>

Leave a Reply