Suppose I am at the main directory which contains script.sh and subdirectories, each of subdirectories contain images.
The script.sh is a script for resizing images. I want to apply this script to every subdirectories, so after searching for solution I created another script which is

SAVEIFS=$IFS #Since the subdirectories contain whitespaces in their name
IFS=$(echo -en "\n\b")
for d in ./*; do
  if [ -d "$d" ]; then
    echo "$d" && cp ./script.sh ./$d/script.sh && cd "$d" && exec sh ./script.sh && cd ..

The problem is this script stops after it's done at the first subdirectory. How can I make it runs for all subdirectories? Or are there better way to make script.sh runs for all subdirectories?


1 Answer 1


find to the rescue!

for d in $(find . -type d); 
    cd $CURDIR/"$d"

Even better... strip the "all files in the directory" stuff from your script, and:

for f in $(find . -type f); 
    ./script.sh "$f"
  • 2
    See Why is looping over find's output bad practice?. Better to use some variant of find . -type d -execdir /path/to/script.sh {} \; (with the variations depending on what, if any, args you want to pass to script.sh)
    – cas
    Commented Mar 14, 2018 at 5:39
  • Thanks, @cas. I find the loop much more comprehensible than having to deal with {} \; and {} + and it's thousand variations.
    – RonJohn
    Commented Mar 14, 2018 at 5:51
  • Did you read the linked Q&A? My comment wasn't about comprehensibility, or the fact that shell loops are the slowest way of looping over any text input, or even about writing fewer lines of code to do the same thing, it was about the fact that there are risks in looping over find's output . Risks that aren't necessary because find has -exec and -execdir.
    – cas
    Commented Mar 14, 2018 at 8:38
  • @cas I understand that. But for me, now, screwing up find esoterica is an existential problem, whereas looping over it's results aren't.
    – RonJohn
    Commented Mar 14, 2018 at 8:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .