Debian Codegraph @

arr-choice.sh

raw symbols SCIP
1 #!/bin/bash
2 # arr-choice.sh
3
4 # Passing arguments to a function to select
5 #+ one particular variable out of a group.
6
7 arr0=( 10 11 12 13 14 15 )
8 arr1=( 20 21 22 23 24 25 )
9 arr2=( 30 31 32 33 34 35 )
10 # 0 1 2 3 4 5 Element number (zero-indexed)
11
12
13 choose_array ()
14 {
15 eval array_member=\${arr${array_number}[element_number]}
16 # ^ ^^^^^^^^^^^^
17 # Using eval to construct the name of a variable,
18 #+ in this particular case, an array name.
19
20 echo "Element $element_number of array $array_number is $array_member"
21 } # Function can be rewritten to take parameters.
22
23 array_number=0 # First array.
24 element_number=3
25 choose_array # 13
26
27 array_number=2 # Third array.
28 element_number=4
29 choose_array # 34
30
31 array_number=3 # Null array (arr3 not allocated).
32 element_number=4
33 choose_array # (null)
34
35 # Thank you, Antonio Macchi, for pointing this out.