已知/etc/hosts文件的内容为:

192.168.1.131 master.test.com

192.168.1.132 agent.test.com

192.168.1.11 server11

192.168.1.111 server111

请用shell脚本实现,怎么才能在输入IP后找到/etc/hosts中对应的唯一的hostname?


方法1:

#!/bin/bash

read -t 8 -p "Please input ip address:" ip
[ -n "`grep "$ip " /etc/hosts`" ] &&\
  echo "The hostname is `grep "$ip " /etc/hosts|awk '{print $2}'`"||\
echo "The "$ip " is not exist !!!"


方法2:

#!/bin/bash

flag=0
exec </etc/hosts
while read line
do
  if [ "$1" == "`echo $line|awk '{print $1}'`" ]
  then
    flag=1
    echo "The $1's hostname is `echo $line|awk '{print $2}'`"
    break
  fi
done
  [ $flag -eq 0 ] && echo "Sorry, not found $1's hostname !!!"


方法3:

#!/bin/bash

awk '{if($1=="'$1'") print "The hostname is " $2}' /etc/hosts


转自:http://oldboy.blog.51cto.com/2561410/760192