You can run commands as different users in Ubuntu using sudo and su.
With sudo
Just use the following params:
- -H to load the Home environment variables of the user.
- -u to run the command as another user.
- -c to execute a bash command.
sudo -H -u billy bash -c 'echo "My name is: $USER, my uid is: $UID"'
Or just become the user using the -i flag to invoke the login shell and -u to define the user:
sudo -i -u USER_NAME
With su
You can achieve the same result using su. The hyphen (“–“) after su creates a new environment with the settings of the new user instead using your own one.
su - billy -c 'echo "My name is: $USER, my uid is: $UID"'
If you run su as root it won’t ask for password.