WP-CLI command to update all plugins and core fails when executed from cron

Understanding this answer requires preliminary knowledge in a system administration and Linux issue named “Environment variables”. Acquiring this knowledge could be done with a didactic Linux book, course, or tutor. If one explanation was bad, seek another.


The problem and the solution:

It seems to happen due to a partial utilization of the PATH environment variable, by cron.

When cron runs it has only the /usr/bin value of this variable, instead the whole set, common in Ubuntu 16.04:

/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

What I did was to add the full location of WP-CLI to the commands (I also splitted the long one-liner command to two short commands):

From:

0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && wp plugin update --all --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && wp core update --allow-root; done

To:

0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done

Note the /usr/local/bin/ right before wp.

To test this works without waiting a whole day I changed the cron schedule from 0 0 * * * (in the first minute, of the first hour, in each day of month, in each month, in each day of week), to this:

* * * * *

(in each minute, in each hour, in each day of month, in each month, in each day of week).

After about 2 minutes I checked one of my websites and saw everything was updated (besides themes, which updating them isn’t included in the two commands I used).