# HG changeset patch # User Franz Glasner # Date 1725105963 -7200 # Node ID ace88a4831f778fd101882a63bcc8e3014405a73 # Parent 277c58d6ffba403cc6b52ef975eeed866ecad920 array.sh: implement array_tryget() for iterating in a shell while loop diff -r 277c58d6ffba -r ace88a4831f7 share/local-bsdtools/array.sh --- a/share/local-bsdtools/array.sh Sat Aug 31 14:04:54 2024 +0200 +++ b/share/local-bsdtools/array.sh Sat Aug 31 14:06:03 2024 +0200 @@ -203,6 +203,52 @@ #: +#: Try to get an array value from a given index +#: +#: Args: +#: $1 (str): The name of the existing array +#: $2 (int): The index +#: +#: Output (stdout): +#: The value at index $2. +#: +#: Returns: +#: 0 (truthy) on success, +#: 1 (falsy) if the given index is out of bounds (i.e. EOD) +#: +#: Exit: +#: Other errors (missing array name, missing index value) are considered +#: fatal and call `_array_fatal` (i.e. `exit`). +#: +array_tryget() { + local _name _index + + local _gvrname _l _value + + [ $# -lt 1 ] && _array_fatal "missing array name" + _name=$1 + _gvrname=${_farr_global_prefix}$1 + [ $# -lt 2 ] && _array_fatal "missing array index" + _index=$2 + + # Check whether the variable already exists + eval _l=\${${_gvrname}__:-__UNSET__} + if [ "${_l}" = "__UNSET__" ]; then + _array_fatal "array \`${_name}' does not exist" + fi + + # check index range + if [ \( "${_index}" -lt 1 \) -o \( "${_index}" -gt ${_l} \) ]; then + return 1 + fi + + eval _value=\"\${${_gvrname}_${_index}}\" + printf "%s" "${_value}" + return 0 +} + + +#: #: Empty an existing array #: #: Args: