Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
exit
... 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?

Thanks.

share|improve this question
    
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

2 Answers 2

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.

share|improve this answer
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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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