Skip to main content Logo

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

Bash - do something in every subdirectory

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

❗ This post is over twelve years old. It may no longer be up to date. Opinions may have changed.

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.

Recently I removed all Google Ads from this site due to their invasive tracking, as well as Google Analytics. Please, if you found this content useful, consider a small donation using any of the options below:

I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $200 credit for 60 days. Spend $25 after your credit expires and I'll get $25!

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