Bash - do something in every subdirectory

16-05-2012 | Remy van Elst


Table of Contents


This little bash script will let you do an action (or actions) in all subdirectories of a folder. It is a small for loop, which I needed for a git cleanup.

Git clean

I have all my git repositories in my ~/git folder. Sometimes those things grow big and I run a git gc on them. Now I had not done that for a few weeks and my git folder was getting huge. Git has a nice command, git gc, which clean up stuff. I don't know how exactly, but I do know it works.

This command will find all directories, 1 level deep. Then it will go into them (pushd), issue the command (git gc) and go back to the above directory (popd).

remy@solaris3 $~/git: for D in `find . -maxdepth 1 -type d`; do pushd $D; echo "==> DIR ${D}, COMMAND: git gc"; git gc; popd; done
Other stuff

You can also use it for other things, like copy a license file to all your software source code directories

remy@solaris3 $~/git: for D in `find . -maxdepth 1 -type d`; do pushd $D; echo "==> DIR ${D}, COMMAND: cp ~/LICENSE ./"; cp ~/LICENSE ./; popd; done

You might want to zip all directories? Check if a file exists? What more to think about?


Tags: bash, for, git, loop,