One Liners: Edit hosts file

How

Add mydomain.test pointing to 127.0.0.1 to your /etc/hosts file use:

grep -q '127.0.0.1 mydomain.test' /etc/hosts ||
  sudo sed -i '$ a 127.0.0.1 mydomain.test' /etc/hosts

To remove it do:

grep -q '127.0.0.1 mydomain.test' /etc/hosts &&
  sudo sed -i '/127.0.0.1 mydomain.test/d' /etc/hosts

Comment it out with:

grep -q '127.0.0.1 mydomain.test' /etc/hosts &&
  sudo sed -i 's/127.0.0.1 mydomain.test/# &/' /etc/hosts

And uncomment it by executing:

grep -q '# 127.0.0.1 mydomain.test' /etc/hosts &&
  sudo sed -i '/# 127.0.0.1 mydomain.test/s/^# //g' /etc/hosts

Add them to your Makefile for ultimate productivity:

IP     := 127.0.0.1
DOMAIN := mydomain.test

.PHONY: domain/add
domain/add:
	@grep -q '$(IP) $(DOMAIN)' /etc/hosts ||
		sudo sed -i '$ a $(IP) $(DOMAIN)' /etc/hosts

.PHONY: domain/remove
domain/add:
	@grep -q '$(IP) $(DOMAIN)' /etc/hosts &&
		sudo sed -i '/$(IP) $(DOMAIN)/d' /etc/hosts

.PHONY: domain/comment
domain/add:
	@grep -q '$(IP) $(DOMAIN)' /etc/hosts &&
		sudo sed -i 's/$(IP) $(DOMAIN)/# &/' /etc/hosts

.PHONY: domain/uncomment
domain/add:
	@grep -q '# $(IP) $(DOMAIN)' /etc/hosts &&
		sudo sed -i '/# $(IP) $(DOMAIN)/s/^# //g' /etc/hosts

So you can quickly use:

make domain/add
make domain/remove
make domain/comment
make domain/uncomment

Or in general with:

make domain/add       IP=127.0.0.1 DOMAIN=mydomain.test
make domain/remove    IP=127.0.0.1 DOMAIN=mydomain.test
make domain/comment   IP=127.0.0.1 DOMAIN=mydomain.test
make domain/uncomment IP=127.0.0.1 DOMAIN=mydomain.test

Why

Using grep before sudo sed means you only need your sudo password if you mutate the file. Clever trick to save you time!

Domains pointing to localhost have to be .test and not something else, more about it in the official RFC: