Write Text to a File Using sudo
A small trick but one that proves invaluable is how to use
sudo to write text out to a file you wouldn’t otherwise have permission to access; useful when you just need to append or replace content in a system file, for example.
As we need to run the append as root, we simply wrap the command in a privileged shell:
$ sudo sh -c 'echo "Add this string to the file" >> /absolute/path/to/file'
Pay attention to the quotation marks used, specifically single quotes to wrap the whole command and double quotes to wrap the text we’re writing to the file.
If instead we want to replace the content of the file we just drop the extra angle bracket as follows:
$ sudo sh -c 'echo "Replace the contents with this string" > /replace/this/file'