1

I have the following bash:

#!/bin/bash
if ["$#" -ne "1"]; then
   echo "Usage: `basename $0` <HOSTNAME>"
   exit 1
fi

IPADDR=`ifconfig | head -2 | tail -1 | cut -d: -f2 | rev | cut -c8-23 | rev`
sed -i -e '1i$IPADDR   $1\' /etc/hosts

But when I cat /etc/hosts:

$IPADDR

How can I deal with such issues?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
MLSC
  • 5,872
  • 8
  • 55
  • 89
  • 1
    There are more reliable ways of extracting the ip address, see for example [Putting IP Address into bash variable. Is there a better way](http://stackoverflow.com/q/6829605/1331399). – Thor Mar 04 '14 at 08:50

3 Answers3

6

Your problem is that variables inside single quotes ' aren't expanded by the shell, but left unchanged. To quote variables you want expanded use double quotes " or just leave off the quotes if they are unneeded like here, e.g.

sed -i -e '1i'$IPADDR'   '$1'\' /etc/hosts

In above line $IPADDR and $1 are outside of quotes and will be expanded by the shell before the arguments are being feed to sed.

Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80
3

The single quotes mean the string isn't interpolated as a variable.

#!/bin/bash
IPADDR=$(/sbin/ifconfig | head -2 | tail -1 | cut -d: -f2 | rev | cut -c8-23 | rev)
sed -i -e "1i${IPADDR}   ${1}" /etc/hosts

I also did the command in $(...) out of habit!

chooban
  • 9,018
  • 2
  • 20
  • 36
0

Refer to sed manual:https://www.gnu.org/software/sed/manual/sed.html

As a GNU extension, the i command and text can be separated into two -e parameters, enabling easier scripting:

The formal usage should be:

sed -i -e "1i$IPADDR\\" -e "$1" /etc/hosts

Bruce Wen
  • 61
  • 1
  • 4