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 am trying to learn bash scripting. I am working on a practical problem and at one point I need to add a line to a file which requires root permission to write.

The code looks like this:

# some code
echo "add this line to the code" >> fileName
# some code

Is it possible to somehow make the script ask for the root password, validate the password, and on successful authentication modify the file? The script should then return to the user mode and continue the command execution.

share|improve this question
add comment

4 Answers 4

up vote 6 down vote accepted

There's a tip in the sudo man page which explains how to do something like this. Here's my one-liner:

#!/usr/bin/bash
sudo sh -c "echo \"add this line to the code\" >> fileName"

Obviously, you'll first have to set up your user to have sudo privileges. The sh shell is used because of the redirection to the root-owned file. I also had to escape the quotes used for the echo command.

share|improve this answer
add comment

su is available on most unix systems and should work:

su root -c 'echo "add this line to the code" >> fileName'
share|improve this answer
add comment

You could use tee with sudo:

echo "add this line to the code" | sudo tee -a filename > /dev/null

echo's output is redirected with | (pipe) to sudo tee. tee reads from standard input and writes to standard output any given file, in this case filename. -a (or --append) makes tee append to files, without it the files would be overwritten. As tee is run with sudo it opens files with root-permissions. Finally, > /dev/null suppresses tee's output to standard output.

One advantage of using tee instead of just starting the whole command including redirection with su -c or sudo sh -c is, that you do not have to change the quoting of the initial command in any way (Quoting lines already containing quotes can get quite ugly at times).

share|improve this answer
add comment

Would do the trick:

ssh host "sudo su root -c 'echo "add this line to the code" >> /etc/hosts'"
share|improve this answer
    
Why ssh? You do not need su with sudo and neither do you need to specify root as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved. –  Adaephon May 14 at 21:26
add comment

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.