Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

For Loop Question 2

Status
Not open for further replies.

Dagon

MIS
Jan 30, 2002
2,301
0
0
GB
This has probably been asked before, but searching for the word "for" is not the easiest thing...

I have a simple for loop such as:

for x in *.log
do
echo $x
done

This works fine except in the situation where there are no log file, in which case it returns the input criterion ("*.log"). I've got round it in the past by putting in a line to exit the loop if what I get back the same string that I was searching for, but I can't help thinking there must be a better way.

 
for x in `ls *.log 2>/dev/null`

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Or...
Code:
ls -1 *.log | while read X
do
   echo ${X}
done
This will do the loop zero times of there is no file to match the pattern.

Hope this helps.
 
This will do the loop zero times
But you get an error message ...
 
Yes Daniel, but if it's just echoing of names, no need to "exec echo", that is kind of costly. The following does exactly the same.

find . -name '*.log' -print

I would also expect Dagon to want to use the names further on in the script so with a "while read":

find . -name '*.log' -print|while read X
do
...
whatever ${X}
...
done

or PHV's "for" method:

for X in `find . -name '*.log' -print`
do
...
whatever ${X}
...
done

HTH,

p5wizard
 
at least my gnu:find on linux
Any posix compliant find should have the default operation set to -print unless the -none operation is involved.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
I agree about the default action "-print", but it doesn't harm if "-print" is specified in a shell script. It just makes the script behave even if "find" doesn't.


HTH,

p5wizard
 
Not if in a script you need to use the found filename more than once. You would need a 'find' script and a separate 'execute' script to use in the '-exec' option... I like to keep my scripts self-contained.

consider this simple example:

find ...|while read name
do
grep "ERROR" $name >>all_errors
grep "WARNING" $name >>all_warnings
mv $name archdir
done

HTH,

p5wizard
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top