Elevated privilege output redirection

If one wants to create a file with some content, one might use:

echo 'my content' > new.conf

In the event that the target file requires elevated privileges, such as root access to write the file, one might think to just slap sudo on the front of it, as ever:

sudo echo 'my content' > new.conf

However, this just runs `echo` as root, and the target file still cannot be written. How might one overcome this?

Create the file as a regular user, then move it on top of the old conf using sudo.

OR sudo a chmod command that will allow writing -- plus, all of this sounds very much like a security breach in the making. Why are you writing to some type of conf file as a plain user? Do you want all unprivileged users to be able to change files that used to be protected?

I wouldn't take things so seriously. Ubuntu for example basically suggests you do all administration through sudo, and creating the config as the normal you is just good hygiene. Just make sure the file you commit is only writable by root!

The shell redirection has higher precedence and is performed before the sudo command.
Try this:

% sudo touch /tmp/f
% sudo > /tmp/f
zsh: permission denied: /tmp/f
% sudo sh -c '> /tmp/f'
%

So your code becomes:

sudo sh -c 'echo "my content" > new.conf'

Ah, nice one. I see you are invoking a new shell to perform the command. It's good that doing so only involves a few extra key presses. I'll have to add "sh -c" to my local memory banks :wink:

Yes, you might also learn about the 'tee' command. This outputs to a every file you name on the command-line AND to stdout. So:

do_some_work | sudo tee outfile.dat

Results in work being sent to outfile.dat, which is create with root permissions.