DEV Community

Shriharsh
Shriharsh

Posted on • Updated on

My Shell Workflow: Executing a command in lots of directories.

Problem

You want to run a shell command in many directories. For example, in my case, I wanted to execute a shell command in lots of directories(approx. 200) to clean up build files.

Solution

Writing a for-loop and running it on the shell did the trick for me.

for d in ./*/ ; do (cd "$d" && mvn clean); done
Enter fullscreen mode Exit fullscreen mode

Explanation

The above for-loop would run cd "$d" && mvn clean in each item of the directory list defined by the path ./*/. $d holds the directory name. You can be creative in defining the list of directories using a complex glob as well.

I hope this helps you as well.

Discussion (6)

Collapse
msoedov profile image
Alex Miasoiedov

find . -name pom.xml -exec mvn clean .... \;

Collapse
shriharshmishra profile image
Shriharsh Author

Thanks! find is something I wish to use more.

Collapse
val_baca profile image
Valentin Baca • Edited on

Very nearly the same, here's my "inall" script:

$ cat ~/bin/inall
#!/bin/sh
# runs given command (all arugments) in each directory of pwd
# example: in a workspace directory with many subfolders:
# $ inall git status

echo $@
for dir in ${PWD}/*
do
    if [ -d $dir ]; then
        echo ""
        echo "$dir"
        cd $dir && $@
        cd - > /dev/null
    fi
done
Collapse
shriharshmishra profile image
Shriharsh Author

cool! neater than what I used!

Collapse
maestromac profile image
Mac Siri

This lil snippet of code is golden. Thanks for sharing!

Collapse
shriharshmishra profile image
Shriharsh Author

Glad you like it :)