Bash – WP-CLI doesn’t run from cronjob

bashcron

I made a bash script that uses WP-CLI and was intended to run from a cronjob. It runs fine from SSH, but fails when run through cron. During debugging I discovered that it was the WP-CLI part that wasn't running. It has no output at all.

I took just the WP-CLI portion of the script and tested it. I've confirmed that WP-CLI is indeed the problem:

/home/username/script/test.sh

cd /var/www/domain.com/ && wp post create --post-title="test" post-content="testing" --post-status=future

Here's an example of the cronjob that was added via crontab -e from the user account: (set to run every minute for testing purposes)

*/1 * * * * sh /home/username/script/test.sh

The script runs perfectly if run from SSH, but when run from the cron it has no output. I've tried adding | mail -s example@foo.bar to the cronjob entry. It sends the output to my email, but there's no output for the wp-cli command. I've also tried adding my username to the cronjob entry between the time data and the command to try to make sure that it was being run as my user. Also, I tried editing the bash script and changing it to mail -s "cool story bro" example@foo.bar and that worked fine, it just completely ignores WP-CLI.

I've been searching for the answer for about 12 hours now. I recently found this answer to someone else's question, which I think might help, but I don't know how to implement it. https://serverfault.com/a/95736

I just found this answer to someone else's question, and it seems like the way to implement the other person's answer, but it didn't work. https://serverfault.com/a/473961 I used exactly what he posted.

This is being run on an up to date Ubuntu server, by the way.

Please explain what the problem is and how to fix it. Or just if you know anything about it, comment or something, I'm pretty desperate at the moment.

Best Answer

Since the answer to my question was posted as a comment instead of an answer, I'm going to answer it myself to help other people find the answer to the question easier.

As per Cyrus's recommendation, I changed the above test.sh to:

cd /var/www/domain.com/ && /usr/local/bin/wp post create --post-title="test" post-content="testing" --post-status=future

Including the full path fixed the issue. However, I don't understand why a script run from a cronjob from username would be executed differently than if run from SSH as that same user.