Length

array_length

Print the number of elements in a named array.

Example

myarr=( a b c )
array_length myarr  # => 3

Arguments

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

Exit codes

  • 0: Always

Output on stdout

  • The element count.

array_count

Count occurrences of a value in a named array.

Example

myarr=( a b a c a )
array_count myarr a  # => 3

Arguments

  • $1 (string): Name of the array variable.
  • $2 (string): The value to count.

Exit codes

  • 0: Always

Output on stdout

  • The number of times the value appears.

array_keys

Print the indices of a named array.

Example

myarr=( a b c )
array_keys myarr
# => 0
# => 1
# => 2

Arguments

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

Exit codes

  • 0: Always

Output on stdout

  • Each index on its own line.

array_entries

Print index:value pairs for all elements in a named array.

Example

myarr=( a b c )
array_entries myarr
# => 0:a
# => 1:b
# => 2:c

Arguments

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

Exit codes

  • 0: Always

Output on stdout

  • Each index:value pair on its own line.

array_print

Print an array's contents in "index: value" format. Works for both indexed and associative arrays. Requires bash 4.3+ for namerefs.

Example

declare -a fruits=( apple banana cherry )
array_print fruits
# 0: apple
# 1: banana
# 2: cherry

Arguments

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

Exit codes

  • 0: Always; 1 Missing argument

Output on stdout

  • "key: value" lines

array_has_key

Return 0 if an associative array contains the given key. Requires bash 4.3+ for namerefs.

Example

declare -A colours=( [red]="#ff0000" )
array_has_key colours red     # 0
array_has_key colours blue    # 1

Arguments

  • $1 (string): Name of the associative array variable.
  • $2 (string): Key to test.

Exit codes

  • 0: Key present; 1 Key absent; 2 Missing argument