How to define hash tables in Bash?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Hash tables, also known as associative arrays or dictionaries, are data structures that store key-value pairs. In shell scripting, Bash version 4 and above provides support for hash tables. This feature allows you to create more complex data structures than the simple arrays available in earlier versions.
Creating and Initializing Hash Tables in Bash
To utilize hash tables in Bash, you first need to declare an associative array. This can be done using the declare command with the -A option. Here is an example:
Once declared, you can add elements to the hash table by specifying keys and their corresponding values:
You can also initialize a hash table at the time of declaration:
Accessing Values
To retrieve a value from a hash table, you can use the following syntax:
This will output the value associated with key1, which is value1.
Listing All Keys and Values
Bash provides ways to extract all keys or values from an associative array:
- Keys: To get all the keys from the hash table:
- Values: To get all the values from the hash table:
Removing Elements
You can remove an element from a hash table by using the unset command:
This command removes the key-value pair where the key is key1.
Operations on Hash Tables
While Bash does not provide direct functions to sort or filter hash tables, you can achieve these tasks through other commands and scripting techniques.
- Sorting: To sort based on keys:
- Filtering: You can use conditions within a loop to filter elements.
Example Use Case: Counting Word Frequency
Hash tables can be extremely useful for tasks such as counting the frequency of words in a text file:
This script reads words from a file words.txt, uses a hash table to count the frequency of each word, and then prints the count for each word.
Quick Reference
- Declare an associative array with
declare -A my_hash_table. - Add or update an entry with
my_hash_table[key]="value". - Read a value with
echo "${my_hash_table[key]}". - List keys with
printf '%s\n' "${!my_hash_table[@]}". - List values with
printf '%s\n' "${my_hash_table[@]}". - Remove an entry with
unset 'my_hash_table[key]'. - Sort keys by piping the key list to
sort.
Conclusion
Associative arrays allow Bash scripts to handle more complex data manipulations, making scripts more powerful and flexible. Whether you’re managing configuration settings, counting items, or processing text data, hash tables provide a robust toolset for scripting challenges.

