Arrays and dict in bash

Posted by chunyang on August 19, 2022
TAGS: #shell

Most languages will have builtin data structures such as array(list) or dict(hashtable). Is it interesting that whether bash has similar choices?

Dict/Hashtable

Create and access

bash version > 4.0

declare -A dict
dict["A"]="B"
dict["C"]="D"

size=${#dict[@]}

key="A"
echo ${dict[${key}]}

declare -A hash
hash=([one]=1 [two]=2 [three]=3)
echo ${hash[one]}

Iterate a dict

Other interesting implementations:

declare -A dict
dict["A"]="B"
dict["C"]="D"

for i in "${!dict[@]}"
do
  echo "key  : $i"
  echo "value: ${dict[$i]}"
done
  • ${!dict[@]} keys
  • ${dict[@]} values

Other implementation

for i in a,b c_s,d ; do
  KEY=${i%,*};
  VAL=${i#*,};
  echo $KEY" XX "$VAL;
done

Array

By separating strings:

for i in a b c
do
    echo $i
done

By definition

a=(a b c)
for i in ${a[@]}
do
    echo $i
done

size=${#a[@]}
size=$((size-1))

for i in `seq 0 ${size}`
do
    echo ${a[$i]}
done

echo ${a[0]}

echo ${a[4]} # Out of range, get empty value

Reference