One Liners: Edit hosts file

How Link to heading

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

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

To remove it do:

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

Comment it out with:

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

And uncomment it by executing:

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

Add them to your Makefile for ultimate productivity:

IP     :=
DOMAIN := mydomain.test

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

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

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

.PHONY: domain/uncomment
	@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= DOMAIN=mydomain.test
make domain/remove    IP= DOMAIN=mydomain.test
make domain/comment   IP= DOMAIN=mydomain.test
make domain/uncomment IP= DOMAIN=mydomain.test

Why Link to heading

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: