简体   繁体   English

bash嵌套循环不起作用

[英]bash nested for loop not working

I've written a bash script to ban country IP blocks from my router. 我写了一个bash脚本来禁止路由器中的国家IP块。

Why is it that the following works: 为什么以下方法起作用:

for ip in $(wget -qO- http://ipdeny.com/ipblocks/data/countries/cn.zone)
do 
    iptables -I wanin -s "$ip" -j DROP
done

But the following in which I nest multiple countries does not? 但是以下我在多个国家/地区嵌套的信息却没有?

for country in CN AD
do 
    for ip in $(wget -qO- http://ipdeny.com/ipblocks/data/countries/$country.zone) 
    do 
        iptables -I wanin -s "$ip" -j DROP
    done
done

See that it's case sensistive. 看到它是有条件的。 You have 你有

for country in CN AD;

See that you are using caps here. 看到您在这里使用大写字母。 If you use 如果您使用

for country in cn ad;

Then it should work. 然后它应该工作。 Try out yourself the link not working upper case zone and working with lower case zone 尝试一下链接不起作用的大写字母区域小写字母的字母区域

Since country is expected to be lowercase you may add declare -l country like this: 由于country应该是小写字母,因此您可以像这样添加declare -l country

declare -l country
for country in CN AD; do 
  for ip in $(wget -qO- http://ipdeny.com/ipblocks/data/countries/$country.zone); do
    iptables -I wanin -s "$ip" -j DROP
  done
done

or use the ${var,,} parameter expansion : 或使用${var,,}参数扩展

for country in CN AD; do 
  for ip in $(wget -qO- http://ipdeny.com/ipblocks/data/countries/${country,,}.zone); do
    iptables -I wanin -s "$ip" -j DROP
  done
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM