Linux is a multi-user operating system that provides robust user management capabilities. It allows you to maintain independent user environments so that everyone can work in a single system without affecting each other’s work. However, as a system administrator, you may need to switch user in Ubuntu to carry out user-specific tasks such as updates and patches. In this article, we will look at different ways to switch user in Ubuntu Linux.
How to Switch User in Ubuntu & Linux
Here are the different ways to switch user in Ubuntu Linux. You can use these commands to switch users in other Linux systems too.
You can easily use su command to switch users in Ubuntu Linux. Here is its syntax
$ su [OPTIONS] [-] [USER [args]]
If you issue su command without any option or arguments, it will switch to root user and you will be required to enter root password to be able to switch to it.
Even after your shell switches to root user, you will continue to work in the same directory instead of being directed to the root user’s home directory.
Use su to switch to different user
You can easily use su command to switch to a different user with the help of -l option. Here is an example to switch to test_user
$ su -l test_user
The above command will prompt you for the password of user test_user. Every time you want to change user, you will be asked for that user’s login password for authentication. The -l option allows you to login as a different user.
Log in with a different shell
When you switch user, by default, su command logs you into the shell that is specified in /etc/passwd file for that user. /etc/passwd lists the default shell for each user. If you want to log into a different user, with a specific shell, you can do so using -s option.
$ su -l test_user -s /bin/bash
The above command will switch you to test_user with bash shell, after successful authentication.
Preserve Environment Variables
If you want to switch user but preserve environment variables of your present login, then use -p option. It will preserve home directory, user, logname, etc. For example if we are logged in as ubuntu user and want to switch to test_user while preserving our environment variables, then here is the command for it.
ubuntu$ su -p test_user
Run command as different user
If you only want to run a command as different user without logging into an interactive shell, then you can use the -c option.
$ su -c cat data.txt
In this article, we have learnt how to switch user in Ubuntu Linux. We have looked several use cases of su command, regarding how to perform different operations, after switching users. You can use su command on almost every Linux out of box.