How to search and execute in sub-directories via shell script

This post shows a way how to execute scripts in all subdirectories via a script. There are many use cases for this, I use it to automate stop/build/start of arbitrary docker containers on one of my servers. In this way I can setup automated server maintenance jobs (e.g. via jenkins) and startup everything without knowing what is deployed on the server.

Page Contents

The script

The following script loops through all sub-directories and searches for stop.sh. If it is present it is executed, otherwise the script echoes that the script was not found in the subdirectory.

#!/bin/bash
for d in $(find . -maxdepth 1 -type d)
do
    if [ $d !=  '.' ]
    then
      cd "$d"
      if [ -f "./stop.sh" ]
      then
        echo "---- --- Executing --- ----"
        sh "./stop.sh"
      else
        echo "---- stop.sh not found ----"
        pwd
      fi
      cd ..
    fi
done
  • Line 2: for loop over all entries returned by the find command. In every turn the result is assigned to variable d (for directory). The find command searches for all directories (-type d) in the current directory (.) with maxdepth 1 (only one level down). This can obviously be changed to search also in more depth, but in that case also other parts of the script need to be changed.
  • Line 4: The script should ignore the anchor for the current directory (represented by dot .).
  • Line 6: Step into the subdirectory with cd.
  • Line 7: If this directory contains the script we want to execute in each subdirectory (stop.sh in this case).
  • Line 9,10: Print and execute stop.sh here.
  • Line 11,12,13: if stop.sh does not exist print out the directory and echo that the script does not exist.
  • Line 15: Go back up to the parent directory for the next turn.

Execution

This is the output of an example run:

~/docker $ ./stop.sh 
---- stop.sh not found ----
/home/user1/docker/testapp
---- --- Executing --- ----
Stopping processor ... done
Removing processor ... done
Removing network processor_default
---- --- Executing --- ----
Stopping webapp ... done
Removing webapp ... done
Removing network webapp_default
~/docker $ 

Leave a Reply

Your email address will not be published. Required fields are marked *