Last active
May 22, 2023 13:56
-
-
Save chr5tphr/6e30ffe991a2163f8acf67c6dc74d18a to your computer and use it in GitHub Desktop.
Get elements from a combination of bash arrays given a flat index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# combiget: get appropriate elements from a combination of arrays given a flat index | |
combiget() { | |
ind="${1:?'No index.'}" | |
arrs=("${@:2}") | |
for (( i = 0 ; i < ${#arrs[@]} ; i++)); do | |
n="$ind" | |
for (( j = i + 1 ; j < ${#arrs[@]} ; j++ )); do | |
declare -n ref="${arrs[$j]}" | |
(( n /= ${#ref[@]} )) | |
done | |
declare -n ref="${arrs[$i]}" | |
export "${arrs[$i]%[sS]}"="${ref[$(( n % ${#ref[@]} ))]}" | |
done | |
} | |
combicount() { | |
arrs=("${@}") | |
n="1" | |
for (( i = 0 ; i < ${#arrs[@]} ; i++)); do | |
declare -n ref="${arrs[$i]}" | |
(( n *= ${#ref[@]} )) | |
done | |
echo "$n" | |
} | |
combiset() { | |
arrs=("${@}") | |
for (( i = 0 ; i < ${#arrs[@]} ; i++)); do | |
declare -n ref="${arrs[$i]}" | |
mapfile -t vars <<<"${ref}" | |
export "${vars[@]}" | |
done | |
} | |
test_combiget() { | |
IDX=25 | |
val1s=(a b c d e) | |
val2s=(1 2 3 4) | |
val3s=(x y z) | |
val4s=(val5=3$'\n'val6=4 val5=5$'\n'val6=6) | |
keys=(val1s val2s val3s val4s) | |
combiget "$IDX" "${keys[@]}" | |
combicount "${keys[@]}" | |
combiset val4 | |
echo "$val1" | |
echo "$val2" | |
echo "$val3" | |
echo "$val5" | |
echo "$val6" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment