已知/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