#!/usr/bin/env bash
q0='[email protected]&password=dfsa54'
declare -A querydict
while IFS== read key value
do
querydict["$key"]="$value"
done < <(echo "$q0" | sed 's/&/\n/g' )
printf "${querydict[email]}\n"
In the above, 's/&/\n/g' is a sed command that replaces every occurrence of & with a new line. We apply this to q0 so that every parameter assignment is on a separate line. The parameter assignments are then read into the while loop. To read each assignment, IFS== read key value is used. IFS== tells read to treat the equal sign as a word separator. Thus, each assignment is broken into two words: the first is the key and the second is the value. These are then assigned to the associative array querydict with the statement querydict["$key"]="$value".
Putting it in a function
bash differs from most modern programming languages in that its facilities for passing complex data into and out of functions are extremely limited. In the method shown below, the associative array, querydict, is a global variable:
#!/usr/bin/env bash
declare -A querydict
populate_querystring_array () {
query="$1"
while IFS== read arg value
do
querydict["$arg"]="$value"
done < <(echo "$query" | sed 's/&/\n/g' )
}
q0='[email protected]&password=dfsa54'
populate_querystring_array "$q0"
printf "${querydict[email]}\n"