$ cat associative_array.sh
Result:
#!/bin/bash
aa=(
'スライム::100'
'キメラ::10'
'犬::20'
'猫::80'
)
total=0
for k in "${aa[@]}"
do
value="${k##*::}"
total=$((total + value))
done
echo "Total: $total"
index=$1
current=0
for k in "${aa[@]}"
do
value="${k##*::}"
current=$((current + value))
if [ $index -le $current ]
then
name="${k%%::*}"
echo "Index $index: $name"
break
fi
done
Commands & Results:
$ ./associative_array.sh 0
Total: 210
Index 0: スライム
$ ./associative_array.sh 1
Total: 210
Index 1: スライム
$ ./associative_array.sh 10
Total: 210
Index 10: スライム
$ ./associative_array.sh 99
Total: 210
Index 99: スライム
$ ./associative_array.sh 100
Total: 210
Index 100: スライム
$ ./associative_array.sh 101
Total: 210
Index 101: キメラ
$ ./associative_array.sh 110
Total: 210
Index 110: キメラ
$ ./associative_array.sh 111
Total: 210
Index 111: 犬
$ ./associative_array.sh 130
Total: 210
Index 130: 犬
$ ./associative_array.sh 131
Total: 210
Index 131: 猫
$ ./associative_array.sh 200
Total: 210
Index 200: 猫
$ ./associative_array.sh 209
Total: 210
Index 209: 猫
$ ./associative_array.sh 210
Total: 210
Index 210: 猫
$ ./associative_array.sh 211
Total: 210