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

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.


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.