Makmy
Makmy

Reputation: 197

Strange result with my array inside a while loop in bash

I would like to fill a simply array in bash inside a while loop.

I try to do this :

read -p " Value : " nb

declare -a array

while [[ $nb != "s" ]]
do
    read -p " Value : " nb
    array+=("$nb")
done

echo ${array[@]}

If I try with 1,2,3,4 and 5 as values, the output is :

Value : 1
Value : 2
Value : 3
Value : 4
Value : 5 ( to stop the loop and display the array )
2 3 4 5 s

Or, I wan this output :

Value : 1
Value : 2
Value : 3
Value : 4
Value : 5
Value : s 
1 2 3 4 5

Can you tell me what is wrong in my script ?

Upvotes: 0

Views: 127

Answers (2)

zwbetz
zwbetz

Reputation: 1100

Your first read is not adding the input to your array. So just keep your read inside the while loop. Then only add the input to the array if it does not equal s.

declare -a array

while [[ $nb != "s" ]]; do 
  read -p "Value: " nb
  if [[ $nb != "s" ]]; then 
    array+=($nb)
  fi 
done 

echo ${array[@]}

Update: terser syntax, thanks to comment by Charles Duffy.

declare -a array

while :; do 
  read -p "Value: " nb
  [[ $nb == s ]] && break
  array+=($nb)
done 

echo ${array[@]}

Upvotes: 0

BernadetteD
BernadetteD

Reputation: 81

The two lines of code inside your while loop need to be swapped.

read -p " Value : " nb

declare -a array

while [[ $nb != "s" ]] do
    array+=("$nb")
    read -p " Value : " nb
done
echo ${array[@]}

Now your first read is put into your array and your last read (to exit the loop) is not put into the array.

Upvotes: 1

Related Questions