Linux: how to run a command as another user
There are two ways to execute a command as another user, using sudo or using su , despite they do the same thing the way how they work is…
There are two ways to execute a command as another user, using sudo or using su , despite they do the same thing the way how they work is very different and this is good because can cover different scenarios!
The sudo command
sudo executes commands as another user based on the configuration of /etc/sudoers. This means that to allow a user to execute a command as another user it must first configured in this file.
Also when we use sudo the user authenicates with their own password and not the user that want to execute the command.
Syntax$ sudo -u <username> commands
- sudo uses the current session environment variables to be passed to <username> , to explicit load <username> environment variables use sudo with the -i parameter.sudo -i -u <username> commands
The su command
su executes commands as another user but requires to know the password of the user you want to be, its the same of logging to the system as this user, executing the commands and exiting the shell.
Syntax$ su - <username> -c "commands"
- - : The dash means use the environment variables of <username>