Created
January 16, 2021 21:40
-
-
Save jayliew/247b004a54462bdd3a99022a23698a3f to your computer and use it in GitHub Desktop.
Cheat sheet for using a bash "dictionary". Also known as a hash or an associative array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
################################################################################ | |
# | |
# Cheat sheet for using a bash "dictionary". Also known as a hash or | |
# associative array. Because the stone ages need modern data structures too. | |
# | |
# jayliew (a) jayliew (.) com | |
# | |
################################################################################ | |
# declare hash / dictionary / associative array | |
declare -A dictionary | |
dictionary["key1"]="value1" | |
dictionary["key2"]="value2" | |
################################################################################ | |
# access an element | |
echo ${dictionary["key1"]} | |
################################################################################ | |
# get all values (1 long string, space delimited) | |
echo ${dictionary[@]} | |
################################################################################ | |
# get all keys (1 long string, space delimited) | |
echo ${!dictionary[@]} | |
################################################################################ | |
# how to iterate through keys | |
for key in "${!dictionary[@]}"; do | |
echo $key | |
done | |
################################################################################ | |
# check if key exists | |
test_key="key3" | |
if [ ${dictionary[${test_key}]+true} ] ; then | |
echo "key exists" | |
else | |
echo "key does NOT exist" | |
fi | |
################################################################################ | |
# function to test if key exists | |
does_key_exist() { | |
local -n arr=$1 # argument passed by reference | |
for key in "${!arr[@]}"; do | |
if [[ $key == $2 ]]; then | |
echo "exists" # this is the actual returned value | |
return 0 # must return to break out of loop (0 status code == success) | |
fi | |
done | |
echo "does_not_exist" | |
return 1 # status code: unsuccessful | |
} | |
# usage: does_key_exist dictionary_name key_name | |
ret_val=$(does_key_exist dictionary "key2") | |
echo "Returned value is: ${ret_val}" | |
################################################################################ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment