Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 522
Lasse Meyer Avatar asked Aug 01 '16 11:08

Lasse Meyer


1 Answers

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.

like image 138
fedorqui 'SO stop harming' Avatar answered Oct 15 '22 11:10

fedorqui 'SO stop harming'