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!

link|improve this question

64% accept rate
feedback

2 Answers

up vote 0 down vote accepted

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).

link|improve this answer
Thanks a ton!!! – evan Jan 20 '11 at 1:42
Why do you suggest the second method when using 'rm' instead of the first? – evan Jan 20 '11 at 1:44
Yes, I just re-ordered them. I think the for dir in $basedir/* way is simpler. – Mikel Jan 20 '11 at 1:47
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 Jan 20 '11 at 1:48
feedback
find Dir1 -mindepth 1 -type d -exec dosomethinghere {} \;
link|improve this answer
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 Jan 20 '11 at 0:48
feedback

Your Answer

 
or
required, but never shown

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