'How to write/retrieve associative dictionary to/from file using Bash?

How do I save/retrieve a key/value associative dictionary variable to a file using Bash?

Rough example that doesn't work:

#!/bin/bash

# Get script directory.
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)

# Import user settings.
source "$SCRIPT_DIR/data/settings.sh"

# Initialize assets file path.
assets_file_path="$SCRIPT_DIR/data/assets_dictionary.sh"

add_asset(){
    #$1=asset symbol.
    #$2=asset name.
    crypto_assets["$1"]="$2"
}

# Saves crypto_assets associative dictionary to file.
# If existing file, overwrites file with new dictionary.
# If no existing file, saves a new file.
save_assets_dictionary(){
    cat $crypto_assets | > "$assets_file_path"
}

# Imports the assets dictionary from file to memory.
import_assets_dicionary(){
    # Import user assets dictionary.
    source "$assets_file_path" || delcare -A crypto_assets # None found.  Write assets to file on user input.
}


Solution 1:[1]

declare -p var will output the statement you can run to get the $var back.

declare -A assoc
assoc=([x]=1 ['y z']=$'2\n3')
declare -p assoc  # declare -A assoc=(["y z"]=$'2\n3' [x]="1" )

Solution 2:[2]

declare -p (choroba's answer) is a good approach, and will handle stuff like new lines in the array data ok, as the output is automatically quoted in a way that can be reused as input.

The output of declare -p is the bash code required to declare the same array, with the same data. This code can be saved to a file.

To declare/load the array stored in the file, source that file in the script.

Here is an example of how to implement it:

# make an example array
declare -A example=(a=[one] b=[two] c=[three])

# save the bash code to declare this array, to a file
declare -p example > /path/to/data/example-dict.bash

# to declare/load the array stored
# in the file, source the file:
. /path/to/data/example-dict.bash

You can also use source file instead of . file.

Remember that the data file is bash code, so it's not practical for anything other than bash to use that file.

There are other methods, which can be good if you need to read or modify the key-value data file with something other than bash (like other languages, programs, etc.).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 choroba
Solution 2 dan