The UNIX and Linux Forums  
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #4 (permalink)  
Old 09-19-2007
cfajohnson's Avatar
cfajohnson cfajohnson is offline Forum Advisor  
Shell programmer, author
  
 

Join Date: Mar 2007
Location: Toronto, Canada
Posts: 2,310
Quote:
Originally Posted by lumdev View Post
I'm having a question about for loops. (bash)

I have the following for example:

for file in `ls *.txt`

That is not the way to loop through files. Not only is ls unnecessary, it will break your script if any filenames contain spaces or other pathological characters. Use the wildcard directly:

Code:
for file in *.txt
Quote:
do
read file ...
done

Now when there is a file present there is no problem, now when there is no file present I get the following output in my standard mail box : "No such file or directory" Script is executed via crontab.

Now I want to catch the above error so I don't get it in my mail any more, but I have no idea how to do this.

I can make an if statement first "if [ -f *.txt ] ...", but there must be a better solution.

No, you cannot do that; it will fail if there is more than one .txt file.

You can use a function:

Code:
is_file() {
   test -f "$1"
}

is_file *.txt &&
 for file in *.txt
 do
   ...
 done
The safest way is to check each file:

Code:
for file in *.txt
do
  [ -f "$file" ] || continue
  ...
done