how to modify /etc/hosts from shell scripts?
Solution 1:
I'd rather not touch /etc/hosts
in terms of parsing and such. I'd simply create a directory called /etc/hosts.d/
and make up some script that takes:
- ip
- name
- aliases
creates one (1) file with one (1) line. The filename will be <ip>.host
and then cat /etc/hosts.d/*host > /tmp/hosts.new && mv /tmp/hosts.new /etc/hosts
. Maybe add an incron
event that watches the /etc/hosts.d/
directory and regenerates /etc/hosts
whenever something happens, that way you'll get rid of old entries too.
Solution 2:
Take a look at augeas. It has a ready-made parser/serializer for the hosts file (that's even in their quick tour guide) and comes with a simple tool to make changes (augtool).