Skip to main content

Raymii.org Logo (IEC resistor symbol) logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

Bash - do something in every subdirectory

Published: 16-05-2012 | Author: Remy van Elst | Text only version of this article


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.

If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)

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 , snippets