Check file exists from a shellscript

Hi,

I have a list of files that I want to check to see if they exist and then count how many of these files exist, I also want to do the same for the files that arent found.

I have done this by creating temp files see below but want ot do this using variables instead:

for FILE in $FILELIST
do
ls -l $OKAYDIR/$FILE >>countload.txt 2>/dev/null
done

LOADCOUNT=`cat countload.txt|wc -l`
cat countload.txt >>results.txt

echo >>results.txt
echo "$LOADCOUNT files loaded">>results.txt

Thanks.

I'd do something like this (in ksh):-

foundc=0
nfoundc=0

for file in $FILELIST
do
   if [[ -s "${file}" ]];then
       # file is found and is > 0 bytes.
       foundc=$(( found + 1 ))
       ...do something else you want...
   else
       # file is not found or is 0 bytes
       nfoundc=$(( nfounc + 1 ))
       ...do something else you want...
   fi
done

print "number of files in [$FILELIST] found = [${foundc}]\n"
print "number of files in [$FILELIST] NOT found = [${nfoundc}]\n"

You can change the -s test for -r (file is readble) -e (file exists) -d (file is directory etc) as you see fit.

Thanks, how would I go about putting the found files and not found files into other variables which I could then echo out?

foundc=0
nfoundc=0
fflist=""
nflist=""

for file in $FILELIST
do
   if [[ -s "${file}" ]];then
       # file is found and is > 0 bytes.
       foundc=$(( found + 1 ))
       fflist="${fflist}\n${file}"
       ...do something else you want...
   else
       # file is not found or is 0 bytes
       nfoundc=$(( nfounc + 1 ))
       nflist="${nflist}\n${file}"
       ...do something else you want...
   fi
done

print "List of found files:\n\n${fflist}\n---------"
print "List of NOT found files:\n\n${nflist}\n-----"

print "number of files in [$FILELIST] found = [${foundc}]\n"
print "number of files in [$FILELIST] NOT found = [${nfoundc}]\n"

I've not tested above so maybe couple of bugs.

You could of course save the outputs to a file instead of a variable.

NOTE: accessing the variable list of files will contain \n whereas printing it out should put each entry on new line.

Thanks, how would I go about putting the found files and not found files into other variables which I could then echo out?

I've just answered that with $fflist and $nflist. :slight_smile:

They should contain a list of files found and a list of files not found.

Let me know if it doesn't work

for i in $1
do
if [ ! -f $i ]; then
let countValue=1
fi
done
This is the code i am using and it is not working. where $1 is my txt file name

Thanks
Supriya

if $1 is your text file name, why should you use a for loop?

#!/bin/bash
echo $1
if [ ! -e $1 ]; then
count=1
echo "not exists"
fi
echo $count

-Devaraj Takhellambam