- - - By CrazyStat - - -

9. June 2017

Automatically run WP-CLI as the correct user

Filed under: Linux,Server Administration,Wordpress — Tags: , , , , , , — Christopher Kramer @ 19:04

You are root, your php runs with a different user for each site / customer e.g. using PHP-FPM. And these users don’t have a shell assigned. So how can you easily run wp-cli with the correct user to avoid permission denied-problems?

This is how: Define an alias for wp in your shell config, e.g ~/.bash_profile like this:

alias wp='sudo -u `stat -c '%U' .` -s -- php /usr/local/wp-cli.phar --path=`pwd` '

This will first run stat -c %U . to get the owner of the current folder. Then it will pass this to sudo to execute the command as this user. You might need to adjust the path to the phar-file.

Relogin so the alias takes effect and have fun! 🙂

Now when you are in the folder of some site and run wp-cli with the wp command, it will always automatically run with the user that is the owner of the wordpress-folder, which should be the user assigned to this site.

This is tested on a Debian Wheezy system. On FreeBSD, you would need to adjust it slightly:

alias wp='sudo -u `stat -f '%Su' .` -s -- php /usr/local/wp-cli.phar --path=`pwd` '

Let me know if this saved your day or you still have some problems.


Try my Open Source PHP visitor analytics script CrazyStat.