Once upon a time I used sed
and tee
combined to alter a privileged file in place. Because the shell itself doesn't have root privileges I had to get creative to write command output into files:
sed -r 'script' "/etc/hosts" | sudo tee "/etc/hosts" 1>/dev/null
At the time, this worked wonderfully. It was only after I started using my hosts file for ad blocking that I realised the pipe is limited to a buffer, after which tee will gladly overwrite the file and the rest of the file will disappear.
I also considered a much simpler version:
sed -r 'script' "/etc/hosts" > "/etc/hosts.tmp" && sudo mv "/etc/hosts.tmp" "/etc/hosts"
Unfortunately, this too won't work, since the file in question is a symlink. A mv
would overwrite the symlink, as opposed to the file underneath.
My current solution is this:
sed -r 'script' "/etc/hosts" | sudo tee "/etc/hosts.tmp" 1>/dev/null &&
sudo cat "/etc/hosts.tmp" | sudo tee "/etc/hosts" 1>/dev/null &&
sudo rm "/etc/hosts.tmp"
Ew! How verbose!
Is there a cleaner way of doing this?