Linux System Administration

0 of 85 lessons complete (0%)

Managing User Accounts

Switching User and Switching Group

You don’t have access to this lesson

Please register or sign in to access the course content.

Commands for Switching Users and Groups in Unix-like Systems

CommandPurposeKey OptionsExample
suSwitch 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
sudoExecute 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
newgrpChange the current group ID during a sessionNoneExample:
1. Switch to the developers group: newgrp developers
sgRun a command with a different group IDgroup (group name)Example:
1. Run ls with developers group ID: sg developers -c "ls /home"

Example Usage:

  1. 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.
  2. 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.
  3. 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.
  4. 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.