Functional

array_compact

Remove empty elements from a named array in place.

Example

myarr=( a '' b '' c )
array_compact myarr
printf '%s\n' "${myarr[@]}"
# => a
# => b
# => c

Arguments

  • $1 (string): Name of the array variable.

Exit codes

  • 0: Always

array_filter

Print elements of a named array matching a glob pattern.

Example

myarr=( apple banana cherry apricot )
array_filter myarr 'a*'
# => apple
# => apricot

Arguments

  • $1 (string): Name of the array variable.
  • $2 (string): Glob pattern to filter by.

Exit codes

  • 0: Always

Output on stdout

  • Matching elements, one per line.

array_map

Apply a function to each element of a named array and print the results.

Example

upper() { printf -- '%s\n' "${1^^}"; }
myarr=( hello world )
array_map myarr upper
# => HELLO
# => WORLD

Arguments

  • $1 (string): Name of the array variable.
  • $2 (string): Name of the function to apply to each element.

Exit codes

  • 0: Always

Output on stdout

  • The result of applying the function to each element, one per line.

array_reduce

Reduce a named array to a single value using a binary function. The function receives the accumulator as $1 and the current element as $2, and must print the new accumulator to stdout. If no initial value is given, the first element is used as the accumulator.

Example

add() { printf -- '%s\n' "$(( $1 + $2 ))"; }
myarr=( 1 2 3 4 5 )
array_reduce myarr add 0
# => 15

Arguments

  • $1 (string): Name of the array variable.
  • $2 (string): Name of the binary function to apply.
  • $3 (string): Optional initial accumulator value.

Exit codes

  • 0: Always

Output on stdout

  • The final accumulated value.