Ubuntu 16.04 GNU bash,版本 4.3.48(1)-release (x86_64-pc-linux-gnu)
我们每天必须多次向服务器添加 ip。我发现自己根据 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
如何更改 IP 地址的最后一个八位字节,同时在该行上添加当前循环的 $seq 值?
我试过这个
#-- 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
该地址不是整数,因此失败。
答案1
我认为使其发挥作用的最小改变是:
ipaddress=${address%.*}.$((${address##*.} + ipnum))
这设置ipaddress
为:
- 删除
address
尾随dot
后跟的任何内容(最后一个八位字节) - 一个点
- 数学表达式
$(( ... ))
添加:- 的前八位字节
address
(通过找到的最后一个点去除尽可能多的字符) ipnum
- 的前八位字节