0

I'm working to create a simple script where I can save each line as a variable for later use. However it didn't go well. Can anybody help me please.

read -p  "Enter the number of user and press [ENTER]:" num
   for ((i=1; i<=$num; i++)); do
           var$i="|-> Line $i"
           echo "var$i"

   done

I'm trying to obtain the output that looks like this

|-> Line 1
|-> Line 2
|-> Line 3
|-> Line 4

2 Answers 2

3

You're not too far off. Just use an array:

read -p  "Enter the number of user and press [ENTER]:" num
for ((i=0; i<$num; i++)); do
    var[$i]="|-> Line $((i+1))"
    echo "${var[i]}"
done

for line in "${var[@]}"
do
    echo "Saved line: $line"
done

where the latter gives an example how to retrieve it later. Also, arrays are zero-indexed and I've adjusted it accordingly.

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

3 Comments

This works perfectly. Thanks a lot ! So what you have done is put them into an array ?
Yeah,your answer do it better.
Yes, this puts them in an array. It also relies on the fact that an undefined variable (when used as an array) acts identically to an empty array. But you could also say var=() above to be more explicit and to clear anything that might have previously been defined in var.
0

Can this meet your requirement?

read -p  "Enter the number of user and press [ENTER]:" num
   for ((i=1; i<=$num; i++)); do
       var_j="|-> Line $i"
       echo $var_j

   done

Comments

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.