Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Assuming I have a directory structure like


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!

share|improve this question
up vote 6 down vote accepted

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

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

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

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

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

share|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
find Dir1 -mindepth 1 -type d -exec dosomethinghere {} \;
share|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

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

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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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