Switching Users
su runs one command as a different account. The account changes for that command only.
Run one command as sam
su runs whoami as sam. The warning says sam has no home folder.
$ su - sam -c 'whoami'The same answer with sudo
sudo -u sam runs whoami as sam too. The answer is sam again.
$ sudo -u sam whoamiClean up
userdel deletes the account sam. groupdel deletes the group devs. Both print nothing.
$ userdel sam
$ groupdel devsExample
$ useradd sam
$ su - sam -c 'whoami'
$ sudo -u sam whoami
$ userdel sam
$ groupdel devsKey points
- Use su with -c to run one command as a different account.
- Use sudo -u sam with a command to run it as sam.
- Both commands print sam, because both run as sam.
- Use userdel with a name to delete an account.
- Use groupdel with a name to delete a group.
- userdel and groupdel print nothing when they work.
- In short, su and sudo run a command as a different account, then the account is yours again.
In this example, useradd makes sam again first. su runs whoami as sam. The warning comes first, because sam has no home folder. The answer is still sam. sudo runs whoami as sam next, and the answer is sam again. userdel deletes sam last. groupdel deletes devs. Both print nothing, so the account and the group are gone.
Note
useradd makes no home folder for sam, so su prints a warning about it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does su - sam -c 'whoami' do?