AndroidDev
AndroidDev

Reputation: 21247

Bash script - change to root then exit root

If I am in the middle running a bash script, is there any way to switch over to root user, process a command, and then exit root mode? For example, I'd like to include these commands in the middle of a bash script:

sudo su
umount /home/user/myMount
exit

The problem is that after the first line runs, the shell goes into root mode, but then stops execution. Of course, I could create and execute a second script at this point, but this defeats the purpose of scripting since I could just type the commands myself.

The other obvious idea is to run the script from with the root user at the outset. However, some of the other commands in this script fail if I am the root user since they would expose security vulnerabilities with this much access.

So, I need a way to get into the root and then exit out of it.

Thanks.

Upvotes: 0

Views: 6169

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84453

Specify a Command

The sudo command can take a command and optional arguments. For example:

sudo umount /home/user/myMount

This will run only the specified command and its arguments as root. If you want to run the command as another user, you can use the -u flag. For example, to run umount as Fred, you could use:

sudo -u fred umount /home/user/myMount

While there are certainly other ways to address this issue, this is by far the simplest and most common.

Upvotes: 2

Elmar Peise
Elmar Peise

Reputation: 15483

In order to perform the umount as root, use

sudo umount /home/user/myMount

Upvotes: 1

Related Questions