在 Bash 循环中生成 IP 地址列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40324698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:26:59  来源:igfitidea点击:

Generating a list of IP addresses in a Bash loop

bash

提问by K.U

I need a list of IP addresses from 130.15.0.0 to 130.15.255.255. I tried this but I realized it will create 255 lists. Can anyone please help me figure this out?

我需要一个从 130.15.0.0 到 130.15.255.255 的 IP 地址列表。我试过了,但我意识到它会创建 255 个列表。任何人都可以帮我解决这个问题吗?

for (( i = 0; i <= 255; i++)) ; do
for (( j = 0; j <= 255; j++)) ; do
LIST="$LIST 130.15.$i.$j"
done
done

回答by Benjamin W.

I'd say that your approach works, but it is very slow1. You can use brace expansion instead:

我会说你的方法有效,但速度很慢1。您可以改用大括号扩展:

echo 135.15.{0..255}.{0..255}

Or, if you want the result in a variable, just assign:

或者,如果你想要一个变量的结果,只需分配:

list=$(echo 135.15.{0..255}.{0..255})

If you want the addresses in an array, you can skip the echoand command substitution:

如果你想要数组中的地址,你可以跳过echo和命令替换:

list=(135.15.{0..255}.{0..255})

Now, listis a proper array:

现在,list是一个合适的数组:

$ echo "${list[0]}"                    # First element
135.15.0.0
$ echo "${list[@]:1000:3}"             # Three elements in the middle
135.15.3.232 135.15.3.233 135.15.3.234


Comments on your code:

对您的代码的评论:

  • Instead of

    list="$list new_element"
    

    it is easier to append to a string with

    list+=" new_element"
    
  • If you wanted to append to an array in a loop, you'd use

    list+=("new_element")
    
  • Uppercase variable names are not recommended as they're more likely to clash with environment variables (see POSIX spec, paragraph four)
  • 代替

    list="$list new_element"
    

    附加到字符串更容易

    list+=" new_element"
    
  • 如果你想在循环中附加到一个数组,你会使用

    list+=("new_element")
    
  • 不建议使用大写变量名,因为它们更有可能与环境变量发生冲突(请参阅POSIX 规范,第 4 段)


1In fact, on my machine, it takes almost six minutes – the brace expansion takes less than 0.1 seconds!

1事实上,在我的机器上,几乎需要 6 分钟 - 支架扩展只需不到 0.1 秒!