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 user john and starts a new login shell. You will be prompted for john‘s password.
Run a command as john:bashCopy codesu -c "ls /home/john" john This runs the ls /home/john command as user john without switching to their shell.
Execute Commands as Another User with sudo:
Run a command as john:bashCopy codesudo -u john ls /home/john This runs ls /home/john as user john, using sudo for privilege escalation.
Start a new login shell as john:bashCopy codesudo -u john -i This starts a new interactive shell as user john, similar to su - john.
Change Group ID with newgrp:
Switch to the developers group:bashCopy codenewgrp developers This changes the current group ID to developers within the current shell session, affecting file creation and permissions.
Run Commands with a Different Group ID using sg:
Run ls with the developers group ID:bashCopy codesg developers -c "ls /home" This runs the ls /home command with the developers group ID.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
Leave a Reply