Bash script to perform an action on each subdirectory in a directory

5

3

Assuming I have a directory structure like

Dir1/
  SubDir1/
  SubDir2/
  SubDir3/

I'd like to be able to pass 'Dir1' to a bash script and then perform an action on all of it's subdirectories (SubDir1, SubDir2, SubDir3).

Thanks for your help!

evan

Posted 2011-01-20T00:39:38.640

Reputation: 363

Answers

7

Given it sounds like you're going to be running tar, the best way is probably:

basedir=$1
for dir in "$basedir"/*; do
    if test -d "$dir"; then
        tar -cvf "$dir".tar "$dir"
        rm -r "$dir"
    fi
done

If you wanted to use find, you should add -maxdepth 1, to avoid creating extra tar files.

basedir=$1
for dir in $(find "$basedir" -mindepth 1 -maxdepth 1 -type d); do
    tar -cvf "$dir.tar" "$dir"
    rm -r "$dir"
done

Also note that in tar -cvf, the name of the output file comes first (right after the f).

Mikel

Posted 2011-01-20T00:39:38.640

Reputation: 7 890

Why do you suggest the second method when using 'rm' instead of the first? – evan – 2011-01-20T01:44:45.703

Yes, I just re-ordered them. I think the for dir in $basedir/* way is simpler. – Mikel – 2011-01-20T01:47:31.633

Ok cool, thanks! I'm new to scripting so I wasn't sure if they were just two ways to do it or there was some other reason to use the one method over the other. – evan – 2011-01-20T01:48:39.567

1

find Dir1 -mindepth 1 -type d -exec dosomethinghere {} \;

Ignacio Vazquez-Abrams

Posted 2011-01-20T00:39:38.640

Reputation: 100 516

Thanks for your answer! So if I wanted to compress each sub directory I could use something like "find Dir1 -mindepth 1 -type d -exec tar -cvf {} ;" What if I wanted to use the name of the sub dir more than once, could I use "-exec tar -cvf {} {}.BACK ;"? Finally, what if I want to run more than one command (like rm {} after the tar) - which is why I was thinking I'd have to use some sort of loop in a bash script. Thanks again!! – evan – 2011-01-20T00:48:44.727

0

If you're using GNU find, you can use -execdir parameter, e.g.:

find . -type d -depth 1 -execdir echo Action on $(pwd)/{} ';'

kenorb

Posted 2011-01-20T00:39:38.640

Reputation: 16 795