The Linux users uses shell to interact with operating systems. In which the Bash (Born Shell) is the most used shell and available default on most systems. Now a days Zsh (Z Shell) is also getting popularity between the users due to its features. In this tutorial you will learn how to run command as another user in Linux/Unix systems.

Running Command As Another User with Su

su (Switch User) command is used to run shell as another user. This command switches to the new user and load their environment. The basic su command looks like below: The above command which you to another user, where you can run commands with that user. But our aim is to run Linux command as another user without switching to them. To do this, check below example. I am currently logged in as root user. You can pass your command with -c parameter. Now, the below example will run “ls” command as user rahul without switching to the user. You can also run multiple commands as another user in Linux, like: In the above command, first prints present working directory with pwd, then create and switches to new directory named “hello”. Again prints the present working directory. All commands are separated with semicolon (;) as we do in general.

Run Command As Another User with Sudo

This is generally used to run command as root user, but you can also use it with other users. Here you don’t need to use any command line switches. Enter the name of user to which you want to run command. After that specificy the command to run as defined user. Syntax: For example, you are writing a shell script, which required to run as non-root user. But you need to restart apache2 service. In that case you can use sudo to run command as root user. Like:

Run Command As Another User with Runuser

You can also use runuser to run commands as another user in Linux systems. This is lesser known commands by the Linux users. Use runuser command to execute commands with the effective user ID and group ID of the defined user. Syntax: Example – for example, run a command as user “rahul” and create directory in his home directory. Then list files under home directory of user ‘rahul’. You can also execute booth commands in a single command. Just add multiple commands wit semicolon separated.

Conclusion

In this tutorial, you have learned to run commands as another user in Linux system. You have learned running commands as another user with the help of su, sudo and runuser Linux commands.