Shell-Script
無法在 shell 腳本中正確地從 IP 地址中提取八位字節
ipfile.txt
格式如下:ServerA 127.0.0.1 ServerB 192.168.1.254 ServerC 4.2.2.1
shell腳本的期望輸出:
ServerA Class A ServerB Class C ServerC Class A
我想不出更好的方法來只提取第一個八位字節。到目前為止,我的腳本是:
#!/bin/bash # Take input IP from file and classify according to classful addressing. while read ip;do octet=$(awk -F'[ .]' '{print $2}' ipfile.txt) if [[ "$octet" -ge 1 && "$octet" -le 127 ]];then echo "ServerA Class A" fi if [[ "$octet" -ge 128 && "$octet" -le 191 ]];then echo "ServerB Class B" fi if [[ "$octet" -ge 192 && "$octet" -le 223 ]];then echo "ServerC Class C" fi done < ipfile.txt
我收到語法錯誤:
./ipclassgen.sh: line 7: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 10: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 13: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 7: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 10: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 13: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 7: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 10: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 13: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 7: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 10: [[: 127 192 4: syntax error in expression (error token is "192 4") ./ipclassgen.sh: line 13: [[: 127 192 4: syntax error in expression (error token is "192 4")
如何在不使用 awk 和指定文件的情況下做到這一點。我也不確定語法錯誤在哪裡。
您將文件逐行讀取到
ip
變數中,但從不使用它。然後將所有行的第二個欄位分配給octet
變數,由<NL>
(\n, 0x0A) 分隔,再次讀取文件。然後在進行測試時bash
偶然發現了多行。octet
請嘗試:while read server ip do octet=${ip%%.*} . . . done < file
另請注意,不硬編碼伺服器名稱而是使用
server
從文件中讀取的變數可能更聰明:if [[ "$octet" -ge 1 && "$octet" -le 127 ]] then echo "$server: Class A" fi
PS:您甚至可以
read
為您拆分線路:while IFS=" ." read server ip1 ip2 ip3 ip4 do if [[ "$ip1" ...