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


i have following problem: in script, must not executed root, have write line newly created, empty file. file in /etc, need elevated privilages write it.

creating file simple:

sudo touch /etc/myfile 

now, using echo write file doesn't work...

sudo echo "something" > /etc/myfile 

... because first part of command (echo) executed sudo, not redirection file.

previously used this...

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

...to add end of file, worked, because file wasn't empty. since sed works line based, doesn't anything, file stays empty.

any suggestions? there way echo somehow? special sed expression? other tools use?

you can use tee:

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

or redirect /dev/null if don't want see output:

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

another option use sh -c perform full command under sudo:

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

regarding doing sed: don't think possible. since sed stream editor, if there no stream, there nothing can it.


Comments