0

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
4
  • 1
    See DontReadLinesWithFor re: the for ip in $(cat ...) idiom, and also the related BashPitfalls #1. Commented Aug 3, 2018 at 17:21
  • Similarly, addr=$(host "$name.$DOMAIN" | grep "has address" | cut -d" " -f4)"; if [[ $addr ]]; then ips+=( "$addr" ); fi would be more reliable. (Does assume you fix your variable case, but that's a thing you should do). Commented Aug 3, 2018 at 17:22
  • 1
    That said, replacing host with dig +short would make this whole thing a lot simpler; do that and you don't need to mess with grep or cut at all. Commented Aug 3, 2018 at 17:23
  • Very interesting. Thanks for the pointer Commented Aug 3, 2018 at 17:34

1 Answer 1

1

To iterate over an array, use

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

See PARAMETERS in man bash.

Sign up to request clarification or add additional context in comments.

12 Comments

Great thanks. Is there a reason why the logged "." is appearing more than 4 times? including the logged size as: 1, 3, 4, 4 instead of the expected 1,2,3,4.
maybe host $name.$DOMAIN | grep "has address" | cut -d" " -f4 returns more than one word?
This line must be failing to add to the list: IPS+=(`host $name.$DOMAIN | grep "has address" | cut -d" " -f4`). If list.txt has 4 lines of input and one of the lines has a space in it, you are going to loop 5 times. Try adding echo "$name" into one of the loops to see. Also, you can check out any error messages by adding 2>> error.txt to the end of host $name.$DOMAIN | grep "has address" | cut -d" " -f4 Error messages will display in error.txt
@Jason, ...the lack of quotes when you add an item means you aren't guaranteed that only (and at most) one will be added per iteration.
@Jason: No, that would concatenate a string, not add a new element to an array.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.