shell 根据输入的IP,找到对应的hostname

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

192.168.1.131 master.test.combash

192.168.1.132 agent.test.comide

192.168.1.11 server11server

192.168.1.111 server111blog

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


方法1:get

#!/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:input

#!/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:it

#!/bin/bash

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


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

相关文章
相关标签/搜索