bashquery-stringassociative-arraybash4ifs

Associative array from querystring in bash?


How do I get an associative array from a query string in Bash? - Attempt:

#!/usr/bin/env bash

# Querystring (implementation stolen from http://stackoverflow.com/q/3919755)

function populate_querystring_array ()
{
    param="$1"
    query_dict="$2"
    #for i in "${array[@]}"; do IFS="=" ; set -- $i; query_dict[$1]=$2; done

    for ((i=0; i<${#param[@]}; i+=2))
    do
        query_dict[${param[i]}]=${param[i+1]}
    done
}

q0='email=foo@bar.com&password=dfsa54'
declare -A querydict
populate_querystring_array "$q0" "$querydict"
printf "$querydict[email]"

Solution

  • Below should work:

    #!/bin/bash
    
    function qrystring() {
        qry=$1
    
        while read key value; do
            arr+=(["$key"]="$value")
        done < <(awk -F'&' '{for(i=1;i<=NF;i++) {print $i}}' <<< $qry | awk -F'=' '{print $1" "$2}')
    }
    
    q='email=foo@bar.com&password=dfsa54'
    declare -A arr
    
    qrystring "$q"
    
    for k in ${!arr[@]}; do
        echo "$k -> ${arr[$k]}"
    done
    

    Explanation:

    Im using a combination of awk commands to split the string into individual records first, then split on the = sign for kv pair.

    I'm using process substitution here otherwise i would be populating a copy of the array.

    EDIT:

    Using a global variable to house array.