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 - john
This switches to userjohn
and starts a new login shell. You will be prompted forjohn
‘s password. - Run a command as
john
:bashCopy codesu -c "ls /home/john" john
This runs thels /home/john
command as userjohn
without 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/john
This runsls /home/john
as userjohn
, usingsudo
for privilege escalation. - Start a new login shell as
john
:bashCopy codesudo -u john -i
This starts a new interactive shell as userjohn
, similar tosu - john
.
- Run a command as
- Change Group ID with
newgrp
:- Switch to the
developers
group:bashCopy codenewgrp developers
This changes the current group ID todevelopers
within the current shell session, affecting file creation and permissions.
- Switch to the
- Run Commands with a Different Group ID using
sg
:- Run
ls
with thedevelopers
group ID:bashCopy codesg developers -c "ls /home"
This runs thels /home
command with thedevelopers
group ID.
- Run