1

I want to send multiple values from console so that individual values are assigned to array indexes in array. Later I can use foreach loop to get those values. Thank you.

example:

 Enter values from 1 to 4:
 1
 2
 3
 4

 arr[0] = 1,
 arr[1] = 2,
 arr[2] = 3,
 arr[3] = 4
Allan
  • 12,117
  • 3
  • 27
  • 51
Arun
  • 25
  • 6

1 Answers1

0

If I give you directly the whole answer, you will not learn anything. Therefore I will give you the building blocks necessary to build the solution and guide you through the building steps.

1) Append to array in bash:

ARRAY=()
ARRAY+=('A')
ARRAY+=('B')

Have a look at: Bash array append

2) read syntax:

read [options] NAME1 NAME2 ... NAMEN

Have a look at: read command

3) Bash loop construct:

while read elem
do
  #If end of inputs (special value for example)
  #break in order to quit the loop
  #do something (append to array)
done 

Have a look at: Bash loops

4) Bash branching (if/else/elif/...) construct

Have a look at: Bash if/else

5) Last step, you need to put everything together:

Create an empty array, loop on the user input, check the input value via a if and break the loop if it reach a specific condition, otherwise add it to the array

Let me know if you are stuck somewhere, I will help you.

Allan
  • 12,117
  • 3
  • 27
  • 51