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

bashscript

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

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