For loop with an array in bash script

I want to use for loop with an array. I using the following command for this:

#! /bin/bash
rm -f /orch/list
arrayVM=($(cat /orch/servers | grep $1 | awk '{print $1}'))
for i in $arrayVM
do echo ${arrayVM[$i]}>>list
done

But when I check the list file I see only the first element of arrayVM array. What's wrong with my command?

2 Answers

The principle error is that for i in $arrayVM sets i to the first element in arrayVM, since there is no index. I am surprised that this does not give an error on the echo command, unless the first array element is numeric.

What you need is the iterative form of for:-

for (( i=0; i<${#arrayVM[*]}; ++i ))
do echo ${arrayVM[$i]}>>list
done

However, this is unnecessarily long-winded: much simpler is:-

for e in "${arrayVM[@]}"
do echo $e>>list
done

This assigns e to each element in turn, without enumerating them.

In the light of Fedorqui's answer, if arrayVM is not needed elsewhere, then there is a much simpler way to create the list file:-

cat /orch/servers | grep $1 | awk '{print $1}' >/orch/list

Or, since the cat is unnecessary:-

grep $1 </orch/servers | awk '{print $1}' >/orch/list
4

If you don't need the data to be stored in an array but you also want to use every record for other things, you can loop normally through the data with a process substitution:

while IFS= read -r value _;
do echo "$value" >> list
done < <(grep "$1" /orch/servers)

With read -r value _ we are storing the first field in $value and the rest in the throw away variable $_.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like