How to add a line to a file which has only root write permission and to continue the script execution

9,884

Solution 1

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.

Solution 2

su is available on most unix systems and should work:

su root -c 'echo "add this line to the code" >> fileName'

Solution 3

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:
9,884

Related videos on Youtube

Alex
Author by

Alex

Updated on September 18, 2022

Comments

  • Alex
    Alex almost 2 years

    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.

  • Adaephon
    Adaephon about 10 years
    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.
  • Ryne Everett
    Ryne Everett over 9 years
    Unlike with sudo, passwords don't seem to get cached with su.
  • miracle173
    miracle173 over 9 years
    @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
    miracle173 over 9 years
    I think you will run into troubles with you double quotes