
09-19-2007
|
|
Shell programmer, author
|
|
|
Join Date: Mar 2007
Location: Toronto, Canada
Posts: 2,310
|
|
Quote:
Originally Posted by lumdev
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:
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
|