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
How to Preserve Command Line Spaces in a Linux Application
Delimited by Comma Using Awk or Sed with the Tags Below
Graphical Diff Programs for Linux
Total Size of the Contents of All the Files in a Directory
How to Count Occurrences of a Word in All the Files of a Directory
How to Clear the Scrollback in the Screen Command
How to Prevent Grep from Printing a Trailing Newline
How to List All Vhosts in Nginx
Running Apt-Get for Another Partition/Directory
How to Make Find and Printf Works in Bash Script
How to Make a Built-In Device Driver in Linux
How to Measure Separate CPU Core Usage for a Process
Check Battery Level of Connected Bluetooth Device on Linux
How to Install Maven into Red Hat Enterprise Linux 6
Docker: Are You Trying to Connect to a Tls-Enabled Daemon Without Tls