MIAOU-BASH is a collection of settings and helpers for leveraging BASH. Developer-friendly, it may be used as solo package with or without the miaou project.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

73 lines
1.7 KiB

#!/usr/bin/env miaou-bash
function array_new {
ref_name="$1"
shift
[[ -v nested_count ]] && ((nested_count++)) || nested_count=1
nested_name="nested_$nested_count"
declare -ga "$nested_name"
declare -gn "$ref_name"="$nested_name"
local -n internal="$nested_name"
internal+=("$@")
}
function array_inspect {
local -n ref="$1"
prefix="${2:-}"
echo "${prefix}array '$1' contains ${#ref[@]} elements"
local i
for i in "${ref[@]}"; do echo "${prefix}-> $i"; done
echo "${prefix}----"
}
function nested_new {
local internal
ref_name="$1"
shift
[[ -v nested_count ]] && ((nested_count++)) || nested_count=1
nested_name="nested_$nested_count"
declare -gA "$nested_name"
declare -gn "$ref_name"="$nested_name"
declare -n internal="$nested_name"
internal['TYPE']='NESTED_ARRAY'
local i=0
local j=0
for j in "$@"; do
internal["$i"]="$j"
i=$((i + 1))
done
}
function nested_inspect {
local internal
declare -n internal=$1
[[ "${internal['TYPE']}" != 'NESTED_ARRAY' ]] && >&2 echo "expected nested array: $1" && return 1
count=${#internal[@]}
count=$((count - 1))
echo "nested '$1' contains $count arrays"
local i
for ((i = 0; i < count; i++)); do
array_inspect "${internal[$i]}" " => "
done
echo ----
}
# initialization
array_new mine1 'Albert' 20
array_new mine2 'Bob' 24
array_new mine3 'Conrad' 31 true
# change values
mine1+=(false)
: "$mine3" # pseudo use fix shellcheck issue
mine3[2]=false
nested_new nested1 mine1 mine2 mine3
nested_inspect nested1
# change nested values
declare -n first="${nested1[0]:?}" # ':?' fix shellcheck issue
first+=("nope")
first[1]=$((first[1] + 5))
nested_inspect nested1