Execute a Command in Every Directory with Bash

Posted by in Software, Tutorial

TL;DR: Use a find-based loop

The other day I was wondering how to execute a command in each sub-directory of a project.

In python, you have os.walk. In C, I would’ve probably written myself something just for fun etc. In shell, I know you have find which is capable of finding all directories (find (dir) -type d). All I need to do is to wrap this in a loop and for this one has two options:

  1. Commmand line style


  2. Script style with a loop

The choice between the two depends of the complexity of the command you want to execute inside.

Scripted approach

My use case was to execute a mvn clean in each directory ( the root dir is the container of all my maven-based development projects). Therefore, my logic would look something along the lines:

The result is:

* if [[ $d != *".git/"* ]]; is true if the found directory doesn’t contain the string ".git/" in it.
* if [ -f "$d/pom.xml" ]; is true if the directory has a pom.xml file.
* The script also shows the directory size before and after executing the loop.


A little experiment: If you find this post and ad below useful, please check the ad out :-)