2

I want to store an entry in the /etc/hosts file for the IP of the box that I am on.

When I run the following command I get:

:-$ hostname
ip-10-55-9-102

I want to store this entry in /etc/hosts as following:

Expected result: 10.55.9.102 ip-10-55-9-102

I tried but so far....

CURRENT SOLUTION:

ip=$(hostname -I | cut -d ' ' -f1); echo "$ip ip-${ip//+([.:])/-}" >> /etc/hosts

Actual result: 10.55.9.102 ip-10.55.9.102

Note: Expected has "-" and Actual has "." between numbers.

Hai Vu
  • 30,982
  • 9
  • 52
  • 84
Saffik
  • 689
  • 9
  • 28

4 Answers4

2

Your logic is good, but you don't use the correct pattern in your string substitution. You should have written the following :

ip=$(hostname -I | cut -d ' ' -f1); echo "$ip ip-${ip//[.:]/-}" >> /etc/hosts
Aserre
  • 4,397
  • 3
  • 30
  • 51
1

How about using awk?

hostname | awk -F- '{printf "%s.%s.%s.%s %s\n", $2, $3, $4, $5, $0}' >> /etc/hosts

The awk command uses the -F- flag to specify the dash as a field separator. The printf command picks out fields #2, 3, 4, 5, along with $0 which is the whole line.

Hai Vu
  • 30,982
  • 9
  • 52
  • 84
0

With plain bash:

ip=$(hostname -I)
ip=${ip%%[[:space:]]*}
printf "%s\tip-%s\n" "$ip" "${ip//./-}" # >> /etc/hosts

Drop the # if it works as intended.

M. Nejat Aydin
  • 3,551
  • 3
  • 9
0

There is a system var $HOSTNAME which is the same as hostname command. So if your hostname contain an ip address you can do this:

ip=${HOSTNAME//ip-} # create 'ip' var from $HOSTNAME and remove 'ip-'
ip=${ip//-/.}       # change '-' to '.' in 'ip' var
printf "$ip\t$HOSTNAME" >> /etc/hosts # add desired string to /etc/hosts

Or using hostname to get ip:

ip=( $(hostname -I) )
printf "$ip\t$HOSTNAME" >> /etc/hosts
Ivan
  • 3,695
  • 1
  • 10
  • 13