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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

for loop vs find 5

Status
Not open for further replies.

razalas

Programmer
Apr 23, 2002
237
0
0
US
Can anyone offer reasons to prefer using find vs using a for loop to process files in a script?

In other words, which of the options below is better?

find
Code:
find . -name "*.ext" -exec do_something {} \;

versus

for loop
Code:
for file in *.ext
do
   do_something $file
done


Code what you mean,
and mean what you code!
But by all means post your code!

Razalas
 
EGP,

good point. I hadn't thought of that.

Thanks!

Code what you mean,
and mean what you code!
But by all means post your code!

Razalas
 
To enlarge on elgrandeperro's point I would say that the guideline is use the for construct unless you want to traverse the directory structure.

Note that the -exec parameter to find opens a new process for each file found - as does your for loop so, for functions that take multiple files the options are
Code:
find . -name "*.exe" | xargs do_something
and
Code:
do_something *.exe

On the internet no one knows you're a dog

Columb Healy
 
Hi

Personally I prefer [tt]find[/tt] because it is much more configurable. For example if I want to process only regular files, with [tt]find[/tt] is just one more switch, but with [tt]for[/tt] I have to add a new command :
Code:
find . [red]-type f[/red] -name "*.ext" -exec do_something {} \;

for file in *.ext
do
   [red][ -f "$file" ] || continue[/red]
   do_something $file
done
Additionally, if there is no file matching the *.ext wildcard, then [tt]find[/tt] will generate no output, while [tt]for[/tt]'s behavior depends on the shell's setting ( [tt]shopt[/tt] [tt]nullglob[/tt] in [tt]bash[/tt] ).

Feherke.
 
If you use + instead of \; , find will not start a new process for each match.
Code:
find . -name "*.ext" -exec do_something {} +
using -execdir is often useful (will execute the command in the containing directory).
For deletion there is even a shortcut:
Code:
find . -name "*.ext" -delete

Yes, talking about gnu/find:
find --version
GNU find Version 4.2.32
Built using GNU gnulib version 8e128ebf42e16c8631f971a68f188c30962818be
Aktivierte Funktionen: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION



don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top