| 1 |
#!/bin/bash |
| 2 |
# embedded-arrays.sh |
| 3 |
# Embedded arrays and indirect references. |
| 4 |
|
| 5 |
# This script by Dennis Leeuw. |
| 6 |
# Used with permission. |
| 7 |
# Modified by document author. |
| 8 |
|
| 9 |
|
| 10 |
ARRAY1=( |
| 11 |
VAR1_1=value11 |
| 12 |
VAR1_2=value12 |
| 13 |
VAR1_3=value13 |
| 14 |
) |
| 15 |
|
| 16 |
ARRAY2=( |
| 17 |
VARIABLE="test" |
| 18 |
STRING="VAR1=value1 VAR2=value2 VAR3=value3" |
| 19 |
ARRAY21=${ARRAY1[*]} |
| 20 |
) # Embed ARRAY1 within this second array. |
| 21 |
|
| 22 |
function print () { |
| 23 |
OLD_IFS="$IFS" |
| 24 |
IFS=$'\n' # To print each array element |
| 25 |
#+ on a separate line. |
| 26 |
TEST1="ARRAY2[*]" |
| 27 |
local ${!TEST1} # See what happens if you delete this line. |
| 28 |
# Indirect reference. |
| 29 |
# This makes the components of $TEST1 |
| 30 |
#+ accessible to this function. |
| 31 |
|
| 32 |
|
| 33 |
# Let's see what we've got so far. |
| 34 |
echo |
| 35 |
echo "\$TEST1 = $TEST1" # Just the name of the variable. |
| 36 |
echo; echo |
| 37 |
echo "{\$TEST1} = ${!TEST1}" # Contents of the variable. |
| 38 |
# That's what an indirect |
| 39 |
#+ reference does. |
| 40 |
echo |
| 41 |
echo "-------------------------------------------"; echo |
| 42 |
echo |
| 43 |
|
| 44 |
|
| 45 |
# Print variable |
| 46 |
echo "Variable VARIABLE: $VARIABLE" |
| 47 |
|
| 48 |
# Print a string element |
| 49 |
IFS="$OLD_IFS" |
| 50 |
TEST2="STRING[*]" |
| 51 |
local ${!TEST2} # Indirect reference (as above). |
| 52 |
echo "String element VAR2: $VAR2 from STRING" |
| 53 |
|
| 54 |
# Print an array element |
| 55 |
TEST2="ARRAY21[*]" |
| 56 |
local ${!TEST2} # Indirect reference (as above). |
| 57 |
echo "Array element VAR1_1: $VAR1_1 from ARRAY21" |
| 58 |
} |
| 59 |
|
| 60 |
print |
| 61 |
echo |
| 62 |
|
| 63 |
exit 0 |
| 64 |
|
| 65 |
# As the author of the script notes, |
| 66 |
#+ "you can easily expand it to create named-hashes in bash." |
| 67 |
# (Difficult) exercise for the reader: implement this. |