在Bash数组中添加元素以供以后打印

时间:2018-08-03 17:05:48

标签: linux bash

我在数组(Add a new element to an array without specifying the index in Bash)上添加了元素,但是得到了意外的结果。我想我在数组中添加元素和/或迭代数组以打印其值时做错了事。

代码:

for name in $(cat list.txt); do
    host $name.$DOMAIN | grep "has address" | cut -d" " -f4
done

for name in $(cat list.txt); do
    echo "."
    IPS+=(`host $name.$DOMAIN | grep "has address" | cut -d" " -f4`)
    echo ${#IPS[@]}
done

for ip in $IPS; do
    echo "IP: $ip"
done

输出:

12.210.145.45
67.20.71.219
75.58.197.10
31.70.88.22
.
1
.
3
.
4
.
4
.
4
IP: 12.210.145.45

预期输出:

输出:

12.210.145.45
67.20.71.219
75.58.197.10
31.70.88.22
.
1
.
2
.
3
.
4
IP: 12.210.145.45
IP: 67.20.71.219
IP: 75.58.197.10
IP: 31.70.88.22

1 个答案:

答案 0 :(得分:1)

要遍历数组,请使用

for ip in "${IPS[@]}" ; do

请参阅man bash中的参数。