Introduction
In the Linux world, the terminal is one of the most powerful tools for managing the system. Often we need to execute actions with the privileges of another user, whether to perform maintenance tasks, test configurations, or access restricted files. The su (switch user) command allows changing user directly from the command line without closing the current session. In this article we will explore its operation, syntax, most common options, and some security recommendations for using it responsibly.
What does the su command do?
The su command starts a new shell under the identity of another user. By default, if no username is specified, su switches to the root user. Unlike sudo, which runs a single command with elevated privileges, su opens a full interactive session, allowing you to execute several successive commands under the same identity.
Basic syntax
The simplest form is:
su [nombre_de_usuario]
If nombre_de_usuario is omitted, the system assumes root. After executing the command, the password of the target user will be requested. Once authenticated, a new shell will open and the prompt will change to reflect the new user.
Most used options
-lo--login: starts a login shell, meaning the user’s profile files (.profile,.bashrc, etc.) are read and the environment is set as if the user had logged in normally.-ccommand or--command command: executes only the specified command and then returns to the original shell, without maintaining an interactive session.-sshell or--shell shell: indicates which shell should be used (e.g.,/bin/zsh) instead of the user's default.-m,-por--preserve-environment: preserves the environment variables of the current user instead of loading the target user’s environment.--helpand--version: display the help and version of the command.
Practical examples
-
- Switch to root and obtain a login shell:
su -l
-
- Switch to user
juanand execute a single command:
- Switch to user
su -c "ls -la /home/juan" juan
-
- Start a shell as
juanpreserving the current environment:
- Start a shell as
su -p juan
-
- Specify a different shell:
su -s /bin/zsh juan
Differences between su and sudo
Although both allow performing actions with another user’s privileges, their behavior is distinct:
- su completely changes user and opens a new shell, requiring the target user’s password.
- sudo runs a single command with another user’s privileges (usually root) using the current user’s password, provided they are authorized in the
/etc/sudoersfile. - In environments seeking to minimize exposure of the root password,
sudois often preferable because it does not require knowing the root key. - When a prolonged session under another user is needed (e.g., to test several scripts),
suis more convenient.
Security best practices
- Use
su -lwhenever you need a clean and complete environment; this prevents unexpected environment variables from influencing the session. - Avoid leaving
susessions
This post is also available in ESPAÑOL.