Switching User and Switching Group
Commands for Switching Users and Groups in Unix-like Systems
| Command | Purpose | Key Options | Example |
|---|---|---|---|
su | Switch user or execute commands as another user | - (start login shell), -c command (run command as another user) | Example: |
1. Switch to user john: su - john | |||
2. Run a command as john: su -c "ls /home/john" john | |||
sudo | Execute commands as another user or root | -u user (run as another user), -i (run as login shell) | Example: |
1. Run a command as john: sudo -u john ls /home/john | |||
2. Start a new login shell as john: sudo -u john -i | |||
newgrp | Change the current group ID during a session | None | Example: |
1. Switch to the developers group: newgrp developers | |||
sg | Run a command with a different group ID | group (group name) | Example: |
1. Run ls with developers group ID: sg developers -c "ls /home" |
Example Usage:
- Switch User with
su:- Switch to user
john:bashCopy codesu - johnThis switches to userjohnand starts a new login shell. You will be prompted forjohn‘s password. - Run a command as
john:bashCopy codesu -c "ls /home/john" johnThis runs thels /home/johncommand as userjohnwithout switching to their shell.
- Switch to user
- Execute Commands as Another User with
sudo:- Run a command as
john:bashCopy codesudo -u john ls /home/johnThis runsls /home/johnas userjohn, usingsudofor privilege escalation. - Start a new login shell as
john:bashCopy codesudo -u john -iThis starts a new interactive shell as userjohn, similar tosu - john.
- Run a command as
- Change Group ID with
newgrp:- Switch to the
developersgroup:bashCopy codenewgrp developersThis changes the current group ID todeveloperswithin the current shell session, affecting file creation and permissions.
- Switch to the
- Run Commands with a Different Group ID using
sg:- Run
lswith thedevelopersgroup ID:bashCopy codesg developers -c "ls /home"This runs thels /homecommand with thedevelopersgroup ID.
- Run
