Bash trick - Echo as sudo
I’ve been working on setting up a new server, and writing some bash scripts to
automate the process. There have been a few cases where I want to write to a
file with sudo permissions. I tried doing:
$ sudo echo "Some content with var: $MY_VAR" >/path/to/file/owned/by/root
But, that fails due to lack of permissions, because while the echo is
run as sudo, the output redirection (which is what writes to the file)
happens just as my current user (without elevated permissions).
Here’s a better way to do it:
$ echo "Some content with var: $MY_VAR" | sudo tee /path/to/file/owned/by/root >/dev/null
There may be entirely different ways to solve this, but this has been working well for me, so I wanted to write it up so I don’t forget about it.