Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active October 24, 2024 23:03
Show Gist options
  • Save ariesmcrae/5bb1bca3f56ca4ce62113b2fd37c6cc8 to your computer and use it in GitHub Desktop.
Save ariesmcrae/5bb1bca3f56ca4ce62113b2fd37c6cc8 to your computer and use it in GitHub Desktop.
Bash v5 scripting: Hash Set example
#!/usr/bin/env bash

set -euo pipefail

declare -A hash_set

# Add elements to the hash set
hash_set["name1"]="Matthew"
hash_set["name2"]="Luke"
hash_set["name3"]="John"

get_name() {
    local input="$1"
    
    if [[ -v "hash_set[$input]" ]]; then
        local name="${hash_set[$input]}"
        echo "$name"
    else
        echo -e "\n\nKey \"$input\" not found in the hash set\n\n" >&2
        return 1
    fi
}

process_name() {
    local filter="name3xxx"
    
    # this avoids the subshell $(...) and capture the result explicitly
    local myname
    if ! myname=$(get_name "$filter"); then
        exit 1
    fi

    echo "show myname: $myname"
}

function main() {
    process_name
    exit 0    
}

main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment