2

I am new to shell scripting. I am trying to create an array of size n, where n is input by the user during the run time.

while [ $i -lt $n ]
do

    echo For person $i enter the name?
    read io
    eval Name[$index]= $io

done

When I try to do this, the values are overwritten every time the loop gets the input from user.

For ex: if person 1 is - Tom,if person 2 is - John. Then when i try to print the names of all person at the end of the script, person 1 name is overwritten with person n th name.(which means, all names are stored in a single variable instead of an array).

Can someone tell me where am i going wrong?

1
  • You can get rid of $index and eval. Simply replace eval Name[$index]= $io with Name=("${Name[@]}" "$io"). Commented Jun 27, 2016 at 19:30

1 Answer 1

3
  • You need to increment i in the loop so that it eventually exits. This line increments i by 1:

    let i+=1
    
  • You don't need to use eval in eval Name[$index]= $io.

  • There is no variable named index (at least not in your code sample). I assume you meant to use i there. (i.e., Name[$index] should be Name[$i])

This code works:

#!/bin/sh -e

Name=()
i=0

while [ $i -lt 4 ]
do
  echo For person $i enter the name?
  read io
  Name[$i]=${io}
  let i+=1
done

echo names:
for n in "${Name[@]}"
do
  echo $n
done
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @tony19.It worked for me.I am trying to print multiple array values inside the same loop, for example: person: 1 - print name,age, dob,etc ..so i followed the same technique of declaring 3 arrays. When i tried to do " echo person 1 {$Name[$i]}" , i am not able to access the corresponding value of the variable Name. rather it just prints "Name[0]" . Is there any syntax for this case?

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.