Lasse Meyer Lasse Meyer -5 years ago 277
Bash Question

How to append line to empty file using sed, but not echo?

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 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download