Adding a line to /etc/hosts via bash

It is easy to append a line to a file in BASH.  I wrote a short script this morning that I can use to add a single line to my servers /etc/hosts pointing any domain I want at the loopback IP address of 127.0.01.

So I thought I would share..

#!/bin/bash
SUCCESS=0                      # All good programmers use Constants
domain=example.com             # Change this to meet your needs
needle=www.$domain             # Fortunately padding & comments are ignored
hostline="127.0.0.1 $domain www.$domain"
filename=/etc/hosts

# Determine if the line already exists in /etc/hosts
echo "Calling Grep"
grep -q "$needle" "$filename"  # -q is for quiet. Shhh...

# Grep's return error code can then be checked. No error=success
if [ $? -eq $SUCCESS ]
then
  echo "$needle found in $filename"
else
  echo "$needle not found in $filename"
  # If the line wasn't found, add it using an echo append >>
  echo "$hostline" >> "$filename"
  echo "$hostline added to $filename"
fi

3 thoughts on “Adding a line to /etc/hosts via bash”

  1. Very nice clean and easy to understand snippet.

    The only addition I have made on my own version is to replace:
    echo “$hostline” >> “$filename”
    with:
    sudo bash -c “echo \”$hostline\” >> \”$filename\””

    As I didn’t want to have to put sudo in front of my bash script nor run it as root, but I did want to user to be prompted for their password.

Leave a Reply

Your email address will not be published. Required fields are marked *