我在数组 ( 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
最佳答案
要遍历一个数组,使用
for ip in "${IPS[@]}" ; do
请参阅 man bash
中的参数。
关于linux - 在 Bash 数组中添加元素以便稍后打印它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51677205/