Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I would like to write a bash script to perform some tasks under root while logging as normal user. Is it possible to have something like this?

#!/usr/bash

sudo -i

<multiple line perform all my sudo command>
...
...
...
exit

<back to my user command, continue some other task>

Of course I can put a sudo every line, but I would like to find out is it possible to do something like above? Thanks.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

How about something simple like this.

#!/usr/bash
sudo bash << EOF
# Everything until EOF is run in a sub-shell
echo 'Hello World'
whoami
EOF
share|improve this answer

Here is a simpler approach:

#!/usr/bash

sudo sh another_script.sh

<continue some other task>

Here is the other script.

#!/usr/bash
<multiple line perform all my sudo command>
...
...
...

If you want to avoid prefixing each command with sudo, you can just include them in another script and call it.

share|improve this answer
    
This will work, but you don't really need a separate file, just a sub-shell. –  Zoredache Feb 19 '12 at 8:23

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.