40 lines
988 B
Bash
Executable File
40 lines
988 B
Bash
Executable File
#!/bin/bash
|
|
|
|
#-------------------------------------------------------------------------------
|
|
# Example 3 for Bash Tips show 17: Using "substring expansion" to extract
|
|
# associative array elements
|
|
#-------------------------------------------------------------------------------
|
|
|
|
#
|
|
# Make two indexed arrays each containing 10 letters. Note: this is not the
|
|
# best way to do this!
|
|
#
|
|
declare -a a1=( $(echo {a..j}) )
|
|
declare -a a2=( $(echo {k..t}) )
|
|
|
|
#
|
|
# Build an associative array using one set of letters as subscripts and the
|
|
# other as the values
|
|
#
|
|
declare -A hash
|
|
for ((i=0; i<10; i++)); do
|
|
hash[${a1[$i]}]="${a2[$i]}"
|
|
done
|
|
|
|
#
|
|
# Display the associative array contents
|
|
#
|
|
echo "Contents of associative array 'hash'"
|
|
for key in "${!hash[@]}"; do
|
|
printf '%s=%s\n' "hash[$key]" "${hash[$key]}"
|
|
done
|
|
echo
|
|
|
|
#
|
|
# Walk the associative array printing pairs of values
|
|
#
|
|
echo "Pairs of values from array 'hash'"
|
|
for ((i=1; i<10; i+=2)); do
|
|
printf '%d: %s\n' "$i" "${hash[*]:$i:2}"
|
|
done
|