get_next_array_index

Function description

The get_next_array_index function, as its name would suggest, may be used to retrieve the next index of an array.

Function parameters

$1 - The name of the array variable.

$2 - The (optional) starting index. If no starting index is supplied then the first index shall be returned.

Function output

The get_next_array_index function will send the next array index, if any, to stdout. If no next index is available then nothing will be sent to stdout.

A successful call to the get_next_array_index function will return in a zero return value. Errors, including no index available, will be indicated by a non-zero exit status.

Example use

Listing 1
  1. #! /bin/bash
  2.  
  3. # We rely on some functions from hacking-bash.sh
  4. [[ -r ${HACKING_BASH_LIB_PATH:=/usr/lib/hacking-bash.sh} ]] && \
  5.     source ${HACKING_BASH_LIB_PATH} || \
  6.     { echo "Unable to find ${HACKING_BASH_LIB_PATH}"; exit 1; }
  7.  
  8. # Create an example array
  9. ARRAY[0]="zero"
  10. ARRAY[1]="one"
  11. ARRAY[4]="four"
  12.  
  13. # Get the first array index (0)
  14. get_next_array_index ARRAY
  15.  
  16. # Get the third array index (4)
  17. get_next_array_index ARRAY 1
  18.  
  19. # Test that the last index is less than or equal to 4
  20. get_next_array_index ARRAY 4 || echo "No index after 4"
Example code demonstrating the get_next_array_index function
max@lisa ./get_next_array_index.sh
No index after 4