Update /etc/hosts File Efficiently
This is my method for updating /etc/hosts. It avoids the traps of using e.g. sudo vi, which is insecure, and file redirection to write to /etc/hosts, which does not work with sudo.
Synopsis
Pipe into tee, or for more control over the result, use sudo -e to open /etc/hosts in an editor and curl the hosts list into the buffer, then edit. Remember to backup /etc/hosts first.
Tee
-
Obtain new hosts file and check it.
curl -O http://winhelp2002.mvps.org/hosts.txt -
Pipe into
tee -ato append directly from the command line.cat hosts.txt | sudo tee -a /etc/hosts # -a appends
Vim
-
Open
/etc/hosts.SUDO_EDITOR=vim sudo -e /etc/hostsNOTE: you might need
sudoeditinstead ofsudo -e. -
Make a new line. Curl the target into the file.
:,!curl -s http://winhelp2002.mvps.org/hosts.txtThe
-ssuppresses curl status messages.
Emacs
-
Open
/etc/hosts.SUDO_EDITOR='emacsclient -a' sudo -e /etc/hostsSee Batsov at Emacs Redux for
other methods.NOTE: you might need
sudoeditinstead ofsudo -e. -
Make a new line. Curl the target into the file.
C-u M-x shell-command curl -s http://winhelp2002.mvps.org/hosts.txt