如何在 bash 循环中使用 1 到 200 范围内的变量
How to use variables in a range from 1 to 200 in loop on bash
我有获取一些记录的脚本:
#!/bin/bash
host_start=test
domain=test.com
for host in "${host_start}"{1..200}."$domain";
do
address=`dig +short $host`
echo "$address = $host"
done
在这种情况下,一切正常。我有:
192.168.1.1 = test1.test.com
192.168.1.2 = test2.test.com
192.168.1.3 = test3.test.com
...
...
...
etc ...
但我想在脚本的开头使用变量,而不是文字 {1..200}
。我这样做了:
t1=1
t2=200
for host in "${host_start}"{$t1..$t2}."$domain";
do
...
在这种情况下,我得到一个错误:
dig: 'test{1..200}.test.com' is not a legal name (empty label)
我的错误在哪里?我该如何解决?
大括号展开发生在变量展开之前,因此您不能将它与变量一起使用。使用循环或 seq
命令。
for ((i=t1; i<=t2; i++)) ; do
host=$host_start$i.$domain
或
for i in $( seq $t1 $t2 ) ; do
host=$host_start$i.$domain
你可能应该这样做:
for ((i=t1; i <= t2; i++)); do
host="${host_start}"$i."$domain"
...
done
我有获取一些记录的脚本:
#!/bin/bash
host_start=test
domain=test.com
for host in "${host_start}"{1..200}."$domain";
do
address=`dig +short $host`
echo "$address = $host"
done
在这种情况下,一切正常。我有:
192.168.1.1 = test1.test.com
192.168.1.2 = test2.test.com
192.168.1.3 = test3.test.com
...
...
...
etc ...
但我想在脚本的开头使用变量,而不是文字 {1..200}
。我这样做了:
t1=1
t2=200
for host in "${host_start}"{$t1..$t2}."$domain";
do
...
在这种情况下,我得到一个错误:
dig: 'test{1..200}.test.com' is not a legal name (empty label)
我的错误在哪里?我该如何解决?
大括号展开发生在变量展开之前,因此您不能将它与变量一起使用。使用循环或 seq
命令。
for ((i=t1; i<=t2; i++)) ; do
host=$host_start$i.$domain
或
for i in $( seq $t1 $t2 ) ; do
host=$host_start$i.$domain
你可能应该这样做:
for ((i=t1; i <= t2; i++)); do
host="${host_start}"$i."$domain"
...
done