shell 脚本 更新或者添加host

脚本可以根据传入的参数进行对 /etc/hosts 更改或者添加host

例如执行 sudo ./changeHost.sh blog.duplicatedcode.com 192.168.1.222

域名是固定的,外网ip不断变化

# !/bin/sh
###################
#@in_url 输入的url
#@in_ip 输入的ip
##########################
in_url=${1}
in_ip=${2}

#更改host
updateHost()
{
# read 
  inner_host=`cat /etc/hosts | grep ${in_url} | awk '{print $1}'`
  if [ ${inner_host} = ${in_ip} ];then
     echo "${inner_host}  ${in_url} ok"
  else
    #替换
     sed -i "s#${inner_host}#${in_ip}#g" /etc/hosts
     if [ $? = 0 ];then
       echo "change ${inner_host} to ${in_ip} ok"
       else 
         inner_ip_map="${in_ip} ${in_url}"
         echo ${inner_ip_map} >> /etc/hosts
         if [ $? = 0 ]; then
           echo "${inner_ip_map} to hosts success host is `cat /etc/hosts`"
         fi
     fi
  fi
}

main()
{
   updateHost
}
main

你可能感兴趣的:(shell 脚本 更新或者添加host)