BASH Scripting, su to www-data for single command

Solution 1:

Just use su - www-data -c 'svnadmin create /svn/repository' in your script run by root. So that only this command is run by www-data user.


Update for future viewers:

In case you receive a "This account is currently not available" error, consider using:

su - www-data -s /bin/bash -c 'svnadmin create /svn/repository'

( @Petr 's valuable mention about -s flag to accommodate www-data user's no login policy )

Solution 2:

With 'su' is probably that request a password, and www-data doesn't have password. I recommend the command sudo:

 sudo -u www-data command

The condition is that your user must be root, or configurated in the sudoers file

Solution 3:

2 Possible approaches:


1) sudo command:

In most cases you will have access to the sudo command and so the solution is simply:

sudo -u target_user target_command


2) su command (if sudo not installed. Ex. alpine-linux images):

su - target_user -c 'target_command'

In case you receive a 'This account is currently not available' error, the user has a no login (shell access) policy in effect. If so, consider using:

su - target_user -s /bin/bash -c 'target_command'

(Based on @Petr 's valuable comment about -s flag to accommodate www-data user's no login policy)

Solution 4:

Use su:

   su [options] [username]

   The options which apply to the su command are:

   -c, --command COMMAND
       Specify a command that will be invoked by the shell using its -c.