如何计算bash

时间:2017-05-15 21:06:27

标签: linux bash shell

我有一个从我的网络获取所有IP-A记录的脚本。

    #!/bin/bash

    host_starting=test
    dns=test.com

    for hosts in "${host_starting}"{1..200}."$dns"; do
    addr=`dig +short $hosts`
    echo "$addr=$hosts"
    done

我有输出:

192.168.1.1=test1.test.com
192.168.1.2=test2.test.com
192.168.1.3=test3.test.com
192.168.1.4=test4.test.com
192.168.1.5=test5.test.com
192.168.1.6=test6.test.com
192.168.1.7=test7.test.com
192.168.1.8=test8.test.com
192.168.1.9=test9.test.com
192.168.1.10=test10.test.com
10.1.1.1=test11.test.com
10.1.1.1=test12.test.com
...
...
...
a lot of 10.1.1.1

我不想展示" 10.1.1.1"。 我可以解决它:

if [ $addr != "10.1.1.1" ]; then

但是,我如何计算地址并制定条件: 如果" 10.1.1.1"重复超过2,我们不应该显示它的地址。

2 个答案:

答案 0 :(得分:1)

如果您只想要特定IP的此行为

#!/bin/bash

# Only IP addresses preinitialized in this associative array are tracked
declare -A seen=( [10.1.1.1]=0 )

host_prefix=test
dns=test.com

for host in "$host_prefix"{1..200}."$dns"; do
  addr=$(dig +short "$host")
  [[ ${seen[$addr]} ]] && {
    (( seen[$addr] += 1 ))
    (( seen[$addr] > 1 )) && continue
  }
  printf '%s\n' "$addr=$host"
done

# Just for the fun of it, let's dump our counters to stderr...
declare -p seen >&2

如果您希望每个 IP

的此行为
#!/bin/bash

declare -A seen=( )

host_prefix=test
dns=test.com

for host in "$host_prefix"{1..200}."$dns"; do
  addr=$(dig +short "$host")
  (( seen[$addr] += 1 ))
  (( ${seen[$addr]} > 1 )) && continue
  printf '%s\n' "$addr=$host"
done

# Just for the fun of it, let's dump our counters to stderr...
declare -p seen >&2

一般说明

declare -A seen定义一个数组,其中索引是字符串,而不是整数。

(( seen[$addr] += 1 ))将与$addr中的地址关联的计数器加1;空键被评估为0。

[[ ${seen[$addr]} ]]使用索引addr查找条目(如果存在),如果该条目映射到非空字符串,则返回truthy值。

答案 1 :(得分:0)

未经测试,但可能是这样的:

occured_for_instance_at=
special_ip=10.1.1.1
for hosts in "${host_starting}"{1..200}."$dns"; do
    addr=`dig +short $hosts`
    if [[ $addr == $special_ip ]]
    then
      occured_for_instance_at=$hosts
    else
      echo "$addr=$hosts"
    fi
done
[[ -n "$occured_for_instance_at ]] && echo "$special_ip=$occured_for_instance_at"

如果您不介意在10.1.1.1未显示的情况下获得空输出行,您可以将其简化为:

special_ip_line=
for hosts in "${host_starting}"{1..200}."$dns"; do
    addr=`dig +short $hosts`
    if [[ $addr == 10.1.1.1 ]]
    then
      special_ip_line="$addr=$hosts"
    else
      echo "$addr=$hosts"
    fi
done
echo "$special_ip_line"