获取dynamicIP然后Grep&Echo主机文件

我在我们公司有一个dns&apachi服务器,它的IP地址是dynamic的,我试图做到以下几点:

#!/bin/bash # Get the dynamic IP (dirty, I know) IP=`host -ta mychangingip.myip.com | perl -nle '/((?:\d+\.?){4})/ && print $1' | head -n1` # Update the hosts file if test -n "$IP"; then grep -v www.thesite.com /etc/hosts > /tmp/hosts echo "$IP www.thesite.com" >> /tmp/hosts cp /tmp/hosts /etc/hosts fi 

到目前为止,这一步工作正常,但是当我尝试:

 #!/bin/bash # Get the dynamic IP (dirty, I know) IP=`host -ta mychangingip.myip.com | perl -nle '/((?:\d+\.?){4})/ && print $1' | head -n1` # Update the hosts file if test -n "$IP"; then grep -v www.thesite.com /etc/hosts > /tmp/hosts grep -v portal.thesite.com /etc/hosts > /tmp/hosts echo "$IP www.thesite.com" >> /tmp/hosts/ echo "$IP portal.thesite.com" >> /tmp/hosts cp /tmp/hosts /etc/hosts fi 

它不能按预期工作,只更新一个条目

更换:

 grep -v www.thesite.com /etc/hosts > /tmp/hosts grep -v portal.thesite.com /etc/hosts > /tmp/hosts 

有:

 grep -v www.thesite.com /etc/hosts > /tmp/hosts2 grep -v portal.thesite.com /etc/hosts2 > /tmp/hosts 

或者,将两行替换为:

 grep -v 'www.thesite.com\|portal.thesite.com' /etc/hosts > /tmp/hosts 

进一步简化

考虑替换这五行:

 grep -v www.thesite.com /etc/hosts > /tmp/hosts grep -v portal.thesite.com /etc/hosts > /tmp/hosts echo "$IP www.thesite.com" >> /tmp/hosts/ echo "$IP portal.thesite.com" >> /tmp/hosts cp /tmp/hosts /etc/hosts 

有了这一行:

 sed -i.bak "/www.thesite.com|portal.thesite.com/ s/[^[[:space:]]*/$IP/" /etc/hosts 

供你参考:

 grep -v 'www.thesite.com' /etc/hosts|grep -v 'portal.thesite.com' >/tmp/hosts echo -e $IP'\t\t'www.thesite.com >> /tmp/hosts echo -e $IP'\t\t'portal.thesite.com >> /tmp/hosts cat /tmp/hosts > /etc/hosts