Last Updated: February 25, 2016
·
1.312K
· ajylee

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

  1. Obtain new hosts file and check it.

    curl -O http://winhelp2002.mvps.org/hosts.txt
  2. Pipe into tee -a to append directly from the command line.

    cat hosts.txt | sudo tee -a /etc/hosts   # -a appends

Vim

  1. Open /etc/hosts.

    SUDO_EDITOR=vim
    sudo -e /etc/hosts

    NOTE: you might need sudoedit instead of sudo -e.

  2. Make a new line. Curl the target into the file.

    :,!curl -s http://winhelp2002.mvps.org/hosts.txt

    The -s suppresses curl status messages.

Emacs

  1. Open /etc/hosts.

    SUDO_EDITOR='emacsclient -a' 
    sudo -e /etc/hosts

    See Batsov at Emacs Redux for
    other methods.

    NOTE: you might need sudoedit instead of sudo -e.

  2. Make a new line. Curl the target into the file.

    C-u M-x shell-command
    curl -s http://winhelp2002.mvps.org/hosts.txt