changeset 505:ace88a4831f7

array.sh: implement array_tryget() for iterating in a shell while loop
author Franz Glasner <fzglas.hg@dom66.de>
date Sat, 31 Aug 2024 14:06:03 +0200
parents 277c58d6ffba
children d1ffc844ceb4
files share/local-bsdtools/array.sh
diffstat 1 files changed, 46 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- 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: