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
  • 11,650
  • 3
  • 27
  • 49
Arun
  • 25
  • 6
  • what have you tried so far? – Allan May 02 '18 at 04:39
  • Advice to newcomers: If an answer solves your problem, please accept it by clicking the large check mark (✓) next to it and optionally also up-vote it (up-voting requires at least 15 reputation points). If you found other answers helpful, please up-vote them. Accepting and up-voting helps future readers. Please see [the relevant help-center article][1] [1]: http://stackoverflow.com/help/someone-answers – Allan May 10 '18 at 02:27

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
  • 11,650
  • 3
  • 27
  • 49