$ /devops

Loop over directories in bash and execute commands

published · 1 minute read · bash linux
Loop over directories in bash and execute commands

How to loop over directories in bash and execute multiple commands

In the following example I’ll show you how to loop over a folder /home/ec2-user/www/ and execute pm2 start command:

#!/bin/bash
for i in /home/ec2-user/www/* ; do
  if [ -d "$i" ]; then
    echo "$i"
    cd $i;
    pm2 start ecosystem.config.js;
  fi
done

Image by CCXpistiavos from Pixabay