I have a script that , among other things, needs to do some stuff as root, like creating a mount folder. I tried:

echo "Linux user password is needed in order to ..."
sudo -s
# also tried:
# sudo su
... code that requires root permission
... code that requires user permission

The problem is that the script stops after the "sudo -s" and continues only after I manually exit the automatically created root shell.

Is there a way to run root shell commands within a user script?


  • Creating a mount folder does not require root-priviledges. If a user has write permissions to a folder he can create directories there. There is propably a better way without sudo or stuff like that. – Nils Oct 17 '11 at 18:34
  • I agree with @Nils, but also... why don't you create a second script with all the functionality that needs root privileges? Then just call it with sudo from the first script. – forcefsck Oct 18 '11 at 20:53

Yes, since things like

sudo mkdir /mnt/mymountpoint

work, you can do

sudo ./myrootscript.sh

and if you check for suitable parameters, your script could even call itself again, so you'd just have one file.

  • 1
    and if you needed to do it as a specific user, you can pass a -u $username to sudo. like sudo -u oracle lsnrctl start or something. – Tim Kennedy Oct 17 '11 at 22:22

You are simply using both sudo and su in a wrong way. If you write just sudo -s or sudo su alone, you will end up with an interactive shell created from inside the script - this is what those comands do.

Since you need a chunk of shell code to be executed as root, you need to wrap it somehow into a single command. Probably the simplest way is to use an explicit subshell:

echo "Linux user password is needed in order to ..."
sudo sh -c '
 ... code that requires root permission

That, of course will cause trouble when you try to use some variables defined elsewhere in your script - in such case, use double quotes instead of single.

But if you only have several commands to be run as root, better use sudo in front of each of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.