我发现了一段用于轮换后缀 IP 的代码,看上去很不错,但是我真的无法让它工作。当我运行它时,出现以下错误:
rotate_postfix_ip.sh: 2: Syntax error: "(" unexpected
我不知道如何修复它,有人可以帮帮我吗?
#!/bin/bash
ips=("64.250.120.128" "64.250.121.241" "64.250.121.242")
length=${#ips[@]}
pos=`cat current.txt`
oldip=${ips[$pos - 1]}
if [ "$length" -eq "$pos" ] ; then
echo "limit reached"
pos=1
else
echo "increment!"
(( pos++ ))
fi
echo "$pos" > current.txt
newip=${ips[$pos - 1]}
echo "prev: $oldip"
echo "new: $newip"
sed -ie "s/smtp_bind_address=$oldip/smtp_bind_address=$newip/g" /etc/postfix/main.cf > /dev/null
service postfix reload
x@debi:~$ cat test.sh
#!/bin/bash
ips=("1" "2" "3")
x@debi:~$ sh test.sh
test.sh: 2: Syntax error: "(" unexpected
x@debi:~$ bash -xv test.sh
#!/bin/bash
ips=("1" "2" "3")
+ ips=("1" "2" "3")
该死,这不是换行符的问题。我用 vim 编辑了一个新文件,但出现了同样的错误。
答案1
只需使用“bash”命令运行脚本即可解决问题,
例如 :bash rotate_postfix_ip.sh
答案2
这就是为什么我总是喜欢始终有效的便携式 POSIX 解决方案......
#!/bin/sh
ips='
64.250.120.128
64.250.121.241
64.250.121.242
'
#####################################################
[ ! -f './current.txt' ] && echo '1' > ./current.txt
nIPS=0
for ip in ${ips}; do nIPS=$(( nIPS + 1 )); done
pos=$(cat ./current.txt)
counter=1
for oldip in ${ips}; do
[ $pos -eq $counter ] && break
counter=$(( counter + 1 ))
done
[ "$nIPS" -eq "$pos" ] && {
echo "limit reached"
pos=1
} || {
echo "increment!"
pos=$(( pos + 1 ))
}
echo "$pos" > current.txt
counter=1
for newip in ${ips};do
[ $pos -eq $counter ] && break
counter=$(( counter + 1 ))
done
echo "prev: $oldip"
echo "new: $newip"
sed -ie "s/smtp_bind_address=$oldip/smtp_bind_address=$newip/g" /etc/postfix/main.cf > /dev/null
service postfix reload