I am working on a script that needs to perform an action in every sub-directory of a specific folder.
What is the most efficient way to write that?
I am working on a script that needs to perform an action in every sub-directory of a specific folder.
What is the most efficient way to write that?
for D in `find . -type d`
do
//Do whatever you need with D
done
A version that avoids creating a sub-process:
for D in *; do
if [ -d "${D}"]; do
echo "${D}" # your processing here
fi
done
Or if your command is a single command this is more concise:
for D in *; do [ -d "${D}"] && my_command; done
Or an even more concise version (thanks @enzotib). Note that in this version each value of D will have a trailing slash:
for D in */; do my_command; done
the accepted answer will break on white spaces if the directory names have them, and the preferred syntax is $()
for bash/ksh. Use GNU find
-exec
option with +;
eg
find .... -exec mycommand +;
#this is same as passing to xargs
or use a while loop
find .... | while read -r D
do
...
done
This will create a subshell (which means that variable values will be lost when the while
loop exits):
find . -type d | while read -r dir
do
something
done
This won't:
while read -r dir
do
something
done < <(find . -type d)
Either one will work if there are spaces in directory names.