1. 程式人生 > >學以致用二十-----試著寫的第一個指令碼

學以致用二十-----試著寫的第一個指令碼

 

今天試著寫了以第一個指令碼。

指令碼的目的是第一次安裝完系統後,自動獲取ip地址。

指令碼如下

  1 #!/usr/bin/bash
  2 #check command ifconfig is right or not found
  3 #check ip dhcp
  4 
  5 net_path=/etc/sysconfig/network-scripts
  6 net_name=$(ls ${net_path} | grep -v 'o$' | grep 'ifcfg')
  7 eth_name=$(ls ${net_path} | grep -v 'o$' | grep 'ifcfg' | cut -c 7-)
  
8 9 if ifconfig &>/dev/null;then 10 net_config=$(ifconfig ${eth_name} | grep inet) 11 if [ "${net_config}" = "" ];then 12 sed -i 's/ONBOOT=no/ONBOOT=yes/g' ${net_path}/${net_name} 13 service network restart 14 else 15 net_ip=$(ifconfig ${eth_name} | grep -v inet6 | grep inet | awk '{print $2
}') 16 echo "The ip is "$net_ip"" 17 fi 18 else 19 echo "ifconfig command not found" 20 fi

 

思路:

1、最小化安裝centos 7.2後,我發現執行ifconfig命令,會提示

因此在執行ifconfig的時候,做了個if判斷

2、   net_name=$(ls ${net_path} | grep -v 'o$' | grep 'ifcfg')

網絡卡名稱。我的虛擬機器網絡卡名稱

思路是通過grep 正則表達來查詢 ifcfg開頭的檔案,但是查出來會有兩個

當時想著用正則表示式,除去行尾為lo的表示式,試了一些方法沒實現。於是採用grep自帶的過濾功能,grep -v   

3、   eth_name=$(ls ${net_path} | grep -v 'o$' | grep 'ifcfg' | cut -c 7-)

ifconfig的引數不是帶網絡卡名,不是  ifcofnig  ifcfg-eno16777728,而是  ifconfig  eno16777728

因此需要獲取eno16777728這個欄位,

思路,採用cut的方式,cut -c   以字元為單位進行分割 

範圍控制:
    n:只有第n項
    n-:從第n項一直到行尾
    n-m:從第n項到第m項(包括m)
    -m:從一行的開始到第m項(包括m)
    -:從一行的開始到結束的所有項
ifcfg-eno16777728 -c 7- 可得到結果 eno16777728

4、 sed -i 's/ONBOOT=no/ONBOOT=yes/g' ${net_path}/${net_name}

sed 替換

5、 net_ip=$(ifconfig ${eth_name} | grep -v inet6 | grep inet | awk '{print $2}')

grep -v  過濾掉 inet6 結合 awk 打印出 ip地址

執行結果:

1、未獲取ip的情況

2、 已經獲取ip地址的情況

指令碼基本實現了我的想法。

再接再厲,多練習,指令碼不像想象當中那麼複雜。