Search code examples
bashshellscriptingbash4

Set key value pairs in a shell script


I have a shell script to bootstrap my machine: https://github.com/pathikrit/mac-setup-script/blob/master/setup.sh

I have these few lines of code to setup git:

git config --global rerere.enabled true
git config --global branch.autosetuprebase always
git config --global credential.helper osxkeychain

I would like to extract that out to an associative array (a dictionary/hashmap) at the top and call that in a single line of code. How can I do that in bash 4+?


Solution

  • # Create the associative array
    declare -A opts
    opts[rerere.enabled]=true
    opts[branch.autosetuprebase]=always
    opts[credential.helper]=osxkeychain
    
    # Use the associative array
    for k in "${!opts[@]}"
    do
        git config --global "$k" "${opts[$k]}"
    done