how.wtf

Create dictionaries or maps in Bash

· Thomas Taylor

bash 4.0 natively supports creating hash tables / maps / dictionaries.

Using maps in Bash

Variables in bash are loosely typed; however, declaring provides a type-like behavior. One of the supported types in bash is an associative array (-A).

To declare an associative array:

1declare -A scores

To declare and instantiate in a single line:

1declare -A scores=( ["peter"]=95 ["sally"]=98 )

Add key/value pairs

Adding key/value pairs to an existing associate array:

1scores["tom"]=85
2
3# using variables
4name="brandon"
5score=50
6scores[$name]=$score

Retrieve key/value pairs

Retrieving key/value pairs from an existing associative array:

1name="peter"
2echo ${scores[$name]} # 95

Update an existing key/value pair

Updating an existing key/value pair in an existing associative array:

1name="peter"
2scores[$name]=100
3echo ${scores[$name]} # 100

Check if a key exists

1name="peter"
2if [ -v scores[$name] ]; then
3    echo "$name exists in the map"
4fi
5# Output: peter exists in the map

Remove a key

1name="peter"
2unset scores[$name]

Iterate map

1for key in "${!scores[@]}"; do
2    echo "$key ${scores[$key]}"
3done

Output:

1tom 85
2brandon 50
3sally 98
4peter 100

#bash  

Reply to this post by email ↪