0

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 ..
  fi
done
IFS=$SAVEIFS

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?

0

find to the rescue!

CURDIR=`pwd`
IFS=$'\n'
for d in $(find . -type d); 
do 
    cd $CURDIR/"$d"
    $CURDIR/script.sh
done

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

IFS=$'\n'
for f in $(find . -type f); 
do 
    ./script.sh "$f"
done
  • 1
    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 Mar 14 '18 at 5:39
  • Thanks, @cas. I find the loop much more comprehensible than having to deal with {} \; and {} + and it's thousand variations. – RonJohn Mar 14 '18 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 Mar 14 '18 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 Mar 14 '18 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.