Issue with for loop

Hi Team,

I have for loop in my shell script. Which basically loop through all files in the directory, When some files are in the directory it works just fine.

But if there are no files at all..still the for loop try to execute. Please help. Below is the code.

#!/bin/ksh 
echo "Program Begin" 
cd /home/bharat
for file in /home/bharat/*.RET
do
 echo "File Name=" $file
done
echo "Program End"

Thanks
Bharat

Try:

for file in /home/bharat/*.RET
do
  if [ -f "$file" ]; then
    echo "File Name= $file"
  fi
done
1 Like

Hi
The find tool is really the best one for such process.
See:

$find tmp/ -type f -name '*' -exec  echo File name is {} \;

# creation of 2 empty files 
$ touch tmp/fileone tmp/filetwo
$ find tmp/ -type f -name '*' -exec  echo File name is {} \;
File name is tmp/fileone
File name is tmp/filetwo

1 Like

Thanks Everyone.

Scrutinizer solution working fine. Below is the code. I will try the other solution too.

#!/bin/ksh 
echo "Program Begin" 
cd /home/bhegde
for file in *.RET
do
  if [ -f "$file" ]; then
    echo "File Name= $file"
  fi
done
echo "Program End"

Note that the two commands:

find/home/bharat -type f -name '*.RET' -exec  echo "File name=" {} \;

and:

for file in /home/bharat/*.RET
do
  if [ -f "$file" ]; then
    echo "File Name= $file"
  fi
done

produce the same results only if there are no regular files in any directories under /home/bharat with names ending in .RET .

The find command will list files in subdirectories, the for loop will not list files in subdirectories.

Thanks Don. I think for loop helps my requirement as i do not want to search the sub directories.

Thanks a lot guys.

Thanks
Bharat