#!/bin/bash #------------------------------------------------------------------------------- # Example 2 for Bash Tips show 19: the mapfile/readarray command #------------------------------------------------------------------------------- # # Declare an indexed array # declare -a map # # Fill the array with a process substitution that generates 10 random numbers, # each followed by a newline (the default delimiter). We remove the newline # characters. # mapfile -t map < <(for i in {1..10}; do echo $RANDOM; done) # # Show the array as a list # echo "map: ${map[*]}" echo # # Declare a new indexed array # declare -a daffs # # Define a string with spaces replaced by underscores # words="I_wandered_lonely_as_a_Cloud_That_floats_on_high_o'er_vales_and_Hills,_When_all_at_once_I_saw_a_crowd,_A_host,_of_golden_Daffodils" # # Fill the array with a process substitution that provides the string. The # delimiter is '_' and we remove it as we load the array # mapfile -d _ -t daffs < <(echo -n "$words") # # Show the array as a list # echo "daffs: ${daffs[*]}" echo # # Fill an array with 100 random dictionary words. Use 'printf' as the callback # to report every 10th word using -C and -c # declare -a big mapfile -t -C "printf '%02d %s\n' " -c 10 big < <(grep -E -v "'s$" /usr/share/dict/words | shuf -n 100) echo # # Report every 10th element of the populated array in the same way # echo "big: ${#big[*]} elements" for ((i = 9; i < ${#big[*]}; i=i+10)); do printf '%02d %s\n' "$i" "${big[$i]}" done exit