Append Line to /Etc/Hosts File with Shell Script

Append line to /etc/hosts file with shell script

Make sure to use the -i option of sed.

-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)

sed -i "2i192.241.xx.xx venus.example.com venus" /etc/hosts

Otherwise,

echo "192.241.xx.xx  venus.example.com venus" >> /etc/hosts

would append the line at the end of the file, which could work as you expect.

Shell script to append new lines to etc/hosts and Apache httpd-vhosts.conf in Mac OSX 10.6

Untested, but it should work:

#!/bin/bash
read -p "New local site name: " SITE
read -p "Site path (ex:/Repositories/myproject/mysite.com/trunk/htdocs): " SITEPATH

#/etc/hosts
cp /etc/hosts /etc/hosts.original
echo -e "127.0.0.1\t${SITE}.local" >> /etc/hosts

#httpd-vhosts.conf
VHOSTSFILE="/etc/apache2/httpd-vhosts.conf"
cp $VHOSTSFILE ${VHOSTSFILE}.original
echo "<VirtualHost *:80>" >> $VHOSTSFILE
echo -e "\tDocumentRoot \"${SITEPATH}\"" >> $VHOSTSFILE
echo -e "\tServerName ${SITE}.local" >> $VHOSTSFILE
echo -e "\tServerAlias ${SITE}.localhost" >> $VHOSTSFILE
echo '</VirtualHost>' >> $VHOSTSFILE

#restart apache

>> redirects the output to the given file, appending the contents to the file. I’m also using -e to allow \t to be expanded to a tab character.

Note that you need to run this script with sudo. I've also included commands to backup the original files before modifying them, just in case.

Append Output of Hostname Command to /etc/hosts

You can use sed to edit the first line of the file:

sed -i "1s/$/ $(hostname | tr '\n' ' ')/" /etc/hosts

python3 - subprocess with sudo to append to /etc/hosts

You can do it in python quite easily once you run the script with sudo:

with open("/etc/hosts","a") as f:
f.write('10.10.10.10 puppetmaster\n')

opening with a will append.



Related Topics



Leave a reply



Submit