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 和指定文件的情况下执行此操作。我也不确定语法错误在哪里。
答案1
您将文件逐行读入ip
变量,但从不使用它。然后将所有行的第二个字段分配给变量octet
,以 (\n, 0x0A) 分隔<NL>
,再次读取文件。然后在进行测试时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" ...