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.


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

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.

| improve this answer | |

su is available on most unix systems and should work:

su root -c 'echo "add this line to the code" >> fileName'
| improve this answer | |
  • Unlike with sudo, passwords don't seem to get cached with su. – Ryne Everett Mar 22 '15 at 22:47
  • @Ryne Everett: I am not familiar with sudo. But the behaviour of 'su' is actually as needed by the script of the OP. Most of the time I use 'su' the other way round: changing from root to another user. In this case no password is needed ast all. – miracle173 Mar 24 '15 at 12:02

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).

| improve this answer | |

Try this This command is available on Unix and Linux.

sudo sh -c "echo 'add this line to the code' >> fileName"

| improve this answer | |

Would do the trick:

ssh host "sudo su root -c 'echo "add this line to the code" >> /etc/hosts'"
| 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 '14 at 21:26
  • I think you will run into troubles with you double quotes – miracle173 Mar 24 '15 at 12:05

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.