Ubuntu 16.04 GNU bash,版本 4.3.48(1)-release (x86_64-pc-linux-gnu)
我们必须每天向服务器添加几次 ips。我发现自己根据 ip 块创建了同一文件的不同变体。
#-- 100.100.100.160/29 - Sun 04/22/18 02-38-pm
#-- -----------------------------------------
auto eth0:0
iface eth0:0 inet static
address 100.100.100.160
netmask 255.255.255.255
auto eth0:1
iface eth0:1 inet static
address 100.100.100.161
netmask 255.255.255.255
auto eth0:2
iface eth0:2 inet static
address 100.100.100.162
netmask 255.255.255.255
auto eth0:3
iface eth0:3 inet static
address 100.100.100.163
netmask 255.255.255.255
auto eth0:4
iface eth0:4 inet static
address 100.100.100.164
netmask 255.255.255.255
auto eth0:5
iface eth0:5 inet static
address 100.100.100.165
netmask 255.255.255.255
auto eth0:6
iface eth0:6 inet static
address 100.100.100.166
netmask 255.255.255.255
auto eth0:7
iface eth0:7 inet static
address 99.100.100.167
netmask 255.255.255.255
所以我想创建一个脚本让我尽可能接近那个文件,所以我写了一个脚本,这里是它的一部分......
#!/bin/bash
#
#-- bash add_ips.sh "eth0" "100.100.100.160" "255.255.255.255" "29"
wDir="/scripts/tools/ips"
ifaceFile="/etc/network/interfaces"
ipFile="${wDir}/ipFile.txt"
nic="${1}"
address="${2}"
netmask="${3}"
block="${4}"
timeStamp="$(date '+%a %D %I-%M-%P')"
if [ ! -n "$4" ]; then
echo 'add_ips.sh nic address mask block ...';
exit 1;
fi
#-- echo the address block on a header line
{
echo "";
echo "#-- IP Block ${address}/${block} - ${timeStamp}";
echo "#-- ----------------------------------------------";
} > "$ipFile"
#-- If a 30/block
if [[ "$block" == "30" ]]; then
start="0"
end="3"
for ipnum in $(seq "$start" "$end"); do
{
echo "auto ${nic}:${ipnum}";
echo "iface ${nic}:${ipnum} inet static";
echo -e "\t address ${address}";
echo -e "\t netmask ${netmask}";
echo "";
} >> "$ipFile"
done
输出接近于我正在寻找的内容,剩下要做的就是更改 IP 地址的最后一个数字。
#-- 100.100.100.160/29 - Sun 04/22/18 02-38-pm
#-- -----------------------------------------
auto eth0:0
iface eth0:0 inet static
address 100.100.100.160
netmask 255.255.255.255
auto eth0:1
iface eth0:1 inet static
address 100.100.100.160
netmask 255.255.255.255
auto eth0:2
iface eth0:2 inet static
address 100.100.100.160
netmask 255.255.255.255
如何在该行上添加当前循环的 $seq 值时更改 ip 地址的最后一个八位字节?
我试过这个
#-- If a 30/block
if [[ "$block" == "30" ]]; then
start="0"
end="3"
for ipnum in $(seq "$start" "$end"); do
ipaddress=$(expr "$address" + "$ipnum")
{
echo "auto ${nic}:${ipnum}";
echo "iface ${nic}:${ipnum} inet static";
echo -e "\t address ${ipaddress}";
echo -e "\t netmask ${netmask}";
echo "";
} >> "$ipFile"
done
fi
地址不是整数,所以它失败了。
我认为使它起作用的最小变化是:
这设置
ipaddress
为:address
尾随dot
后面的任何内容(最后一个八位字节)$(( ... ))
:address
(通过它找到的最后一个点去除尽可能多的字符)ipnum