11

I have the following problem: in a script, that must not be executed as root, I have to write a line to a newly created, empty file. This file is in /etc, so I need elevated privilages to write to it.

Creating the file is simple:

sudo touch /etc/myfile

Now, just using echo to write to the file like so doesn't work...

sudo echo "something" > /etc/myfile

... because only the first part of the command (echo) is executed with sudo, but not the redirection into the file.

Previously I used something like this...

sudo sed -i -e "\$aInsert this" /etc/differntfile

...to add to the end of the file, which worked, because the file wasn't empty. But since sed works line based, it doesn't do anything, the file stays completely empty.

Any suggestions? Is there a way to do this with echo somehow? Any special sed expression? Any other tools I could use?

2 Answers 2

11

You can use tee:

echo "something" | sudo tee /etc/myfile   # tee -a to append

Or redirect to /dev/null if you don't want to see the output:

echo "something" | sudo tee /etc/myfile > /dev/null

Another option is to use sh -c to perform the full command under sudo:

sudo sh -c 'echo "something" > /etc/myfile'

Regarding doing this with sed: I don't think it is possible. Since sed is a stream editor, if there is no stream, there is nothing it can do with it.

3
  • 1
    This addresses the problem. Short and straight ++
    – sjsam
    Aug 1, 2016 at 11:53
  • 1
    Great, this is a lot easier than I expected. Aug 1, 2016 at 11:53
  • 2
    If you use variables in the command being executed with sudo sh -c, you have to use double quotes. Aug 1, 2016 at 11:58
5

If you're willing to upgrade from sed (which I also think cannot do this) to awk (GNU awk 4.1.0 or higher to be precise), it can be done like this:

sudo gawk -i inplace '{ print } ENDFILE { print "something" }' /etc/myfile

The alternatives given by the accepted answer are probably easier; I just needed something like this for a use case where I could just use a simple shell command (so no redirection), and the file had to be passed as a single standalone argument (so no sh -c which has the target file embedded inside its single argument). Unlike sed, awk also handles an incomplete last line (which is missing the trailing newline) without adding such.

This uses the inplace awk source library; see man 3am inplace for details.

2
  • 1
    This answer unlike accepted one correctly handles the situation when the last line of the file is not terminated with the new line character. Thanks!
    – Alek
    Jul 28, 2020 at 6:57
  • 1
    man 3am inplace is worthwhile reading for people who wonder what the heck is going on here. ;)
    – dannysauer
    Aug 26, 2020 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.