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?
If you're using GNU sed, you could use its -i
in-place edition flag, so that the results of its execution is directly saved to the file it process. Then you just have to sudo
the sed
command and you should be fine.
Additionnaly to write the file rather than the link, use sed's --follow-symlinks
flag.
In other cases, check this answer to a similar question on SO.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments