su
The su (substitute user or switch user) command allows you to run commands with the privileges of another user. By default, if no user is specified, su defaults to the root user.
Basic Syntax
su [OPTIONS] [USERNAME]
Common Flags/Options
| Option | Description |
|---|---|
-, -l, --login | Start the shell as a login shell with an environment similar to a real login (loads profiles and changes directory to the user's home). |
-c, --command=COMMAND | Pass a single command to the shell and return to the original user immediately after execution. |
-s, --shell=SHELL | Run a specific shell instead of the user's default shell. |
Real-world Examples
1. Switch to root user
Running su without any arguments will prompt for the root password. However, it preserves the current user's environment variables (like $PATH and $HOME).
su
2. Switch to root with a login environment (Recommended)
Using the - (hyphen) flag simulates a full login as the target user. It changes to the root home directory (/root) and loads the root user's $PATH and environment variables.
su -
3. Switch to another specific user
If you need to act as another user (e.g., to test permissions or run an application as a service account), specify their username. You will be prompted for their password, not yours (unless you are root).
su - alice
4. Run a single command as another user
You can execute a specific command as another user and immediately return to your own shell.
su -c 'ls -l /root' root
(You will be prompted for the root password, the command will run, and you will be returned to your prompt).
5. su vs sudo su
If the root password is disabled (common in Ubuntu/Debian), su alone will fail. Instead, you can use sudo to invoke su, using your password instead of the root password.
sudo su -