su Command: Tutorial & Examples

Switching user accounts

The su command, short for substitute user, is a command-line utility in Linux that allows you to switch from one user account to another without logging out and back in. This command is often used by system administrators to perform tasks as the root user, but it can also be used to switch to any other user account on your system.

Why is the su Command Important?

The su command is important because it provides an efficient way to perform tasks that require different user permissions. For instance, a system administrator might need to edit a system file owned by the root user, or a developer might need to test a script as a different user. Instead of logging out and logging back in as the desired user, you can use the su command to switch users in the same shell session.

It can help to solve certain problems like incorrect file permissions or application testing.

Basic Usage of the su Command

The basic syntax of the su command is su [options] [username]. If no username is given, the command assumes you want to switch to the root user. To switch to another user, you provide the username as an argument.

Example:

su
Password:

This prompts you for the root password. If you enter it correctly, you get a root shell.

su john
Password:

This prompts you for the password of the user 'john'. If you enter it correctly, you get a shell as user 'john'.

Common Parameters for the su Command

The su command has several parameters that modify its behavior:

  • -, -l, --login: These options start a login shell after switching the user. A login shell resets most environment variables, providing a clean base.
  • -c, --command: This option runs the command specified in the argument, then exits. It's useful for running a single command as another user.

Example:

su - john -c 'whoami'
john

In this example, the whoami command is run as user 'john', and then the su command exits.

Understanding the Output of the su Command

The su command does not have a typical output, as it's primarily used to switch users in the shell. However, it will prompt for a password and may print an error message if the password is incorrect or the user does not exist.

Example:

su non_existent_user
su: user non_existent_user does not exist

In this case, the su command attempted to switch to a user that does not exist, and therefore printed an error message.

Conclusion

Understanding and using the su command is essential for efficient Linux server management. It allows you to quickly switch between users and perform tasks with different permissions, without the need to log out and back in. Whether you're a system administrator or a developer, the su command is a powerful tool in your Linux toolkit.

The text above is licensed under CC BY-SA 4.0 CC BY SA