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.
vi sites.sh
- Add code and then save.
:wq
chmod
and make executablechmod 766 sites.sh
- 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