Loop through an array

Today I needed to loop through the output of a command on the WP CLI. The most simple way I could think to do that was to save the output of the command into an array and loop through it.

What I did was use wp site list to get the subsites on a WordPress Multisite. I needed to pass each of those sites as an argument to a command and give it some time in between each execution since it was going to be database intensive. Here is what worked out well.

#!/bin/bash

subsites=($(wp site list --field=url))

for i in "${subsites[@]}"
do
wp my_command --url="$i"
sleep 5
done

Save the above into a file.

  1. vi sites.sh
  2. Add code and then save. :wq
  3. chmod and make executable chmod 766 sites.sh
  4. Execute it ./sites.sh | tee site.log

Update

Some of the amazing devs at work helped to modify the loop a bit to make it better for logging.

!/bin/bash

sites=($(wp site list --field=url --path=/var/www))
for i in "${sites[@]}"
do
    domain=$(echo "$i" | awk -F/ '{print $3}')
    wp my_command --url="$i" | tee /path/to/file-"$domain".log
done

Ireland Day 5

Troubleshooting WordPress Permalinks

Troubleshooting WordPress Permalinks

WordPress Core

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.