Post

Arrays and dict in bash

Arrays and dict in bash

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

1
2
3
4
5
6
7
8
9
10
11
12
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:

1
2
3
4
5
6
7
8
9
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

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

Array

By separating strings:

1
2
3
4
for i in a b c
do
    echo $i
done

By definition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

This post is licensed under CC BY 4.0 by the author.