What is it?
BashHash is a BASH loadable built-in (like a plug-in or module) that exposes some useful features of GLib's GHashTable interface. It allows one to create and manipulate hash tables in the BASH process space using a true hash table implementation.
Requirements: bashhash uses GLib version 2.16 or later.
Documentation - Loading/Unloading a BASH built-in
# to load a loadable built-in bash$ enable -f /path/to/binary/builtin builtin # to unload a built-in bash$ enable -d builtin
Documentation - Subcommands
- insert
- Insert key/value pairs into a hash table. When you insert an entry into a table that does not yet exist, the table is created. Multiple key/value pairs can be specified on the command line. Ensure that you quote properly so that bash doesn't split your data in undesired ways.
- lookup
- Print the values associated with specified keys. You can specify multiple keys to print.
- remove
- Remove the key/value pair associated with the specified keys. Multiple keys may be specified. Deleting all key/value pairs in a table does not delete the table itself. To delete a table, you must use destroy.
- destroy
- Free all memory associated with a table. This deletes all key/value pairs in the table as well as the table itself.
- keys
- Print the list of keys in the specified table
- tables
- Print the list of existing tables
- dupkey
- Sets your preference for how duplicate keys are handled. Valid settings are either 'fail' or 'overwrite.' Without any parameters, the current setting will be displayed. The default is to overwrite.
- iterate
- Create an iterator. This allows you to easily loop through all key/value pairs in the table entirely inside the bash process space. The only other way to get data from a table into a variable is via command substitution which requires a subshell.
Example 1 - Inserting data
bashhash insert MyTable1 key1 value1 key2 value2 keyN valueN bashhash insert MyTable1 "Key With Spaces" "Value With Spaces" bashhash insert MyFiles hosts "$(</etc/hosts)" resolve.conf "$(</etc/resolv.conf)"
Example 2 - Performing Lookups
bashhash lookup MyTable1 key1 keyN # command substitution HOSTSFILE=$( bashhash lookup MyFiles hosts )
Example 3 - Removing key/value pairs
bashhash remove MyTable1 keyN key2 bashhash remove MyFiles hosts
Example 4 - Destroying tables
bashhash destroy MyTable1 MyFiles
Example 5 - Iterators
while bashhash iterate MyTable1 MyIter1 MyKey MyValue do echo "'$MyKey'" is the key for "'$MyValue'" done