Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

First of all, I'm totally new in this Linux world. So, please consider this when you read. I got a 10 to 20 lines of bash code which I need to run periodically. Now yesterday, I've been trying to put those lines in a single bash file so that I can just run them in a single command. But I got stuck at a point because the code contains some operations that can only run with a shell login, like 'cd /root' for instance. Now, every time I run them I need to login to a shell using 'sudo -s' after some point. Here is a part of my codes.

cd ~
cp -Rf $worthy_folders /root/
sudo -s
cd /root
sudo chown -R root:root $worthy_folders

Obviously I can not write them in a bash file as they are. That just prompts me for password and need to press several enter. And also the 'sudo cd' doesn't work. So, my question is, there a way to write those commands in a single bash file and just run them?

share|improve this question

1 Answer 1

You could put the whole thing into a file, say myscript.sh, then run the whole thing with sudo:

$ sudo myscript.sh

that way the sudo happens before any of the script. If that isn't acceptable, then you can have sudo execute a few commands at a time:

$ sudo bash -c "cd /root; chown -R root:root $worthy_folders"

This isn't much different, though, but at least you can have a small subset of commands run with elevated privileges instead of all of the commands.

And just as a tip - yeah, it's annoying to be prompted in the middle of a script for a password, and if there is a possibility of a race condition, can be dangerous. You can have sudo validate you by calling it with the -v flag. This will prompt you for your password if required and reset the timestamp to restart the timeout specified in your sudoers file.

share|improve this answer
    
Thanks @Paul, sudo myscript.sh works!!! Thanks a million! –  Prativasic Oct 7 '11 at 6:05

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.