#!/bin/bash #------------------------------------------------------------------------------- # Example 4 for Bash Tips show 17: Using "substring expansion" to extract # associative array elements #------------------------------------------------------------------------------- # # Make two indexed arrays each containing 6 random words. Note: this is not # the best way to do this! # declare -a a1=( $(for word in $(grep -E -v "'s$" /usr/share/dict/words | shuf -n 6); do echo $word; done) ) declare -a a2=( $(for word in $(grep -E -v "'s$" /usr/share/dict/words | shuf -n 6); do echo $word; done) ) # # Build an associative array using one set of words as subscripts and the # other as the values # declare -A hash for ((i=0; i<6; 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<6; i+=2)); do printf '%d: %s\n' "$i" "${hash[*]:$i:2}" done