For loop statement - catch error

I'm having a question about for loops. (bash)

I have the following for example:

for file in `ls *.txt`
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.

Thx.

I think the use of the 'if' statement is a perfectly reasonable solution. You need some kind if conditional statement to determine whether or not your file exists and an 'if' would be OK

Check for the actual file in the loop

  for file in *.txt
  do
     if test -f $file
     then
        read file ...
     fi
  done

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:

for file in *.txt

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

You can use a function:

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

is_file *.txt &&
 for file in *.txt
 do
   ...
 done

The safest way is to check each file:

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

Thx for the answers.

I used the solution with the function, now I don't get any "No such file or directory" output anymore.

Thx for the help cfajohnson.