I am adding elements on an array (Add a new element to an array without specifying the index in Bash) but I am getting an unexpected result. I suppose I am doing something wrong when adding elements in the array and/or when iterating the array to print its values.
Code:
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
Output:
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
Expected output:
Output:
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 $(cat ...)idiom, and also the related BashPitfalls #1.addr=$(host "$name.$DOMAIN" | grep "has address" | cut -d" " -f4)"; if [[ $addr ]]; then ips+=( "$addr" ); fiwould be more reliable. (Does assume you fix your variable case, but that's a thing you should do).hostwithdig +shortwould make this whole thing a lot simpler; do that and you don't need to mess withgreporcutat all.