The su (substitute user) command allows switching to another user account, typically used to gain root privileges or perform tasks as another user.
The sg (switch group) command lets you execute commands as a specific group, which is useful for group-based access control.
su nikhilPassword:
๐น After entering the correct password for nikhil, the shell switches to nikhil's environment.
su -๐น Switches to root user, loading root's environment.
su -c 'whoami' nikhilnikhil
๐น Runs whoami as nikhil without switching to their shell.
export MY_VAR="Hello"
su -m nikhil -c 'echo $MY_VAR'Hello
๐น Keeps the current environment when switching users.
su -s /bin/bash nikhil๐น Switches to nikhil using /bin/bash as the shell.
su -l nikhil๐น Loads nikhilโs complete login environment.
su --helpUsage: su [OPTION]... [USER] [ARGUMENTS]
Switch to another user account.
Options:
-c, --command=COMMAND pass COMMAND to the invoked shell
-m, --preserve-environment do not reset environment variables
-s, --shell=SHELL use SHELL instead of the default
-l, --login make the shell a login shell
-h, --help display this help message and exit
-V, --version output version information and exit
The sg (switch group) command allows executing commands as a different group, useful for group-based access control.
sg developers -c 'whoami'nikhil
๐น Runs whoami with the developers group privileges.
sg admin -c 'echo "Hello, Admins!"'Hello, Admins!
๐น Runs the echo command with admin group permissions.
sg users -c 'groups'nikhil : nikhil users
๐น Lists all groups the user nikhil belongs to.
| Command | Description |
|---|---|
su nikhil |
Switch to user nikhil |
su - |
Switch to root with full environment |
su -c 'whoami' nikhil |
Run whoami as nikhil |
su -m nikhil -c 'echo $MY_VAR' |
Preserve environment when switching users |
su -s /bin/bash nikhil |
Use /bin/bash as the shell for nikhil |
su --help |
Display help information |
sg developers -c 'whoami' |
Run whoami as developers group |
sg admin -c 'echo "Hello!"' |
Run a command with admin group privileges |
sg users -c 'groups' |
Show groups the user belongs to |