Before getting started, ensure that you have access to the shell of a Linux system; any Linux distribution will do just fine. In this guide, we are running Ubuntu 18.04.
Equally crucial is to make sure that you have a shell script with execute permissions. We have a simple shell script called welcome.sh that requests a user’s name and prints it out to the terminal. Here’s a sneak peek.
How to run a shell script as another user
Ordinarily, running a shell script as the currently logged-in user is quite a breeze. Simply call the shell script as follows:
But how would you run the script as another user apart from yourself? To achieve this, simply use the syntax shown where the otheruser is the different user you want to run the script.
Suppose we want to run the script as the linuxways user. The command to be executed will be:
To confirm that the other user has executed the script, we will run the command as shown.
In this case, our other user is linuxways, so we shall invoke the command.
The $USER and $UID variables print the username and the UID of the user running the script. If in doubt or in case you want to verify this, you can view the /etc/passwd file and search for the user’s details as follows.
Here is a summary of the output from both commands. Notice how the username and the UID from running the shell script match those in the /etc/passwd file.
If you wondered how to run a shell script as another user, we are hopeful that your search has now come to an end.