Unix bash script to check if the files exists in the directory

As a server administrator I seldom have to check to see if a file exists in the directory. But what if you have a long list of files that you need to check for? Checking for the existence of many many files manually could prove to be tedious and repetitive task. It would be so easy if you could automate this task, but fear not as I have created a script to automate this process. It would have taken me hours and severe case of carpal tunnel syndrome to manually check for files, but with this handy script it only took a matter of minutes.

Here is the script below, simply cut and paste it into your unix editor.

#!/bin/bash
# Andrew Lin, www.gamescheat.ca
# This script will get the input from a file
# and check to see if the files exists.

# files=”/facebook/login/craigslist /facebook/login/freeones /youtube/myspace/meghan_mccain”

INPUTFILE=”/facebook/login/games”
files=”$(cat $INPUTFILE)”

for i in $files
do

if [ -e $i ];
then
echo “File Exists $i” >> /youtube/myspace/yahoo-result
else
echo “File does not exists $i” >> /youtube/myspace/yahoo-result
fi

done

#files=”/facebook/login/craigslist /facebook/login/freeones /youtube/myspace/meghan_mccain”
The # symbol at the beginning of the line means the line is a comment. In this case if you wanted to check for a short list of files you can simply enter the file names and path like this.

INPUTFILE=”/facebook/login/games”
Define the variable INPUTFILE with the name and path of the file games. This file contains the names of files you wish to check for.

files=”$(cat $INPUTFILE)”
The variable file contains the contents of the file games.

for i in $files
do

The for loop will make the variable i equal the first line of $files, then execute the command following do. The counter is then incremented and i is then equal the second line of $files, and then the commands after do is executed again.

if [ -e $i ];
then
echo “File Exists $i” >> /youtube/myspace/yahoo-result
-e means if the file name contained in the variable $1 exists, then write File Exists and the name and path of the file into the file /youtube/myspace/yahoo-result.

else
echo “File does not exists $i” >> /youtube/myspace/yahoo-result

If not then write file does not exists and the path of file into /youtube/myspace/yahoo-result.

done
After the for loop has reached the end of $files, then done exixts the loop.

1 comment for “Unix bash script to check if the files exists in the directory

Comments are closed.