#!/bin/bash #------------------------------------------------------------------------------- # Example 1 for Bash Tips show 20: deleting individual array elements #------------------------------------------------------------------------------- # # Seed the random number generator with a nanosecond number # RANDOM=$(date +%N) echo "Indexed array" echo "-------------" # # Create indexed array and populate with ad ae ... cf # declare -a iarr mapfile -t iarr < <(printf '%s\n' {a..c}{d..f}) # # Report element count and show the structure # echo "Length: ${#iarr[*]}" declare -p iarr # # Unset a random element # ind=$((RANDOM % ${#iarr[*]})) echo "Element $ind to be removed, contents: ${iarr[$ind]}" unset "iarr[$ind]" # # Report on the result of the element removal # echo "Length: ${#iarr[*]}" declare -p iarr echo echo "Associative array" echo "-----------------" # # Create associative array. Populate with the indices from the indexed array # using the array contents as the subscripts. # declare -A aarr for (( i = 0; i <= ${#iarr[*]}; i++ )); do # If there's a "hole" in iarr don't create an element [[ -v iarr[$i] ]] && aarr[${iarr[$i]}]=$i done # # Report element count and keys # echo "Length: ${#aarr[*]}" echo "Keys: ${!aarr[*]}" # # Use a loop to report array contents in sorted order # for key in $(echo "${iarr[@]}" | sort); do echo "aarr[$key]=${aarr[$key]}" done # # Make another contiguous indexed array of the associative array's keys. We # don't care about their order # declare -a keys mapfile -t keys < <(printf '%s\n' ${!aarr[*]}) # # Unset a random element. The indexed array 'keys' contains the keys # of the associative array so we use the selected one as a subscript. We use # this array because it doesn't have any "holes". If we'd used 'iarr' we might # have hit the "hole" we created earlier! # k=$((RANDOM % ${#keys[*]})) echo "Element '${keys[$k]}' to be removed, contents: ${aarr[${keys[$k]}]}" unset "aarr[${keys[$k]}]" # # Report final element count and keys # echo "Length: ${#aarr[*]}" echo "Keys: ${!aarr[*]}" declare -p aarr exit