0

I have to to parse a query string in bash; I found many solutions online, but I've a big problem when the the asterisk is a "value" o "key".

1 - Example that works

$ PARAMS="key1=val1&key2=val2&key3=val3&key4=val4"
$ ARRAY=(${PARAMS//[=&]/ })
$ echo ${ARRAY[@]}
key1 val1 key2 val2 key3 val3 key4 val4
$

2 - Example that does not work (key4 is equal to *)

$ PARAMS="key1=val1&key2=val2&key3=val3&key4=*"
$ ARRAY=(${PARAMS//[=&]/ })
$ echo ${ARRAY[@]}
key1 val1 key2 val2 key3 val3 key4 file.txt file2.txt file3.txt ...
$

The problem is that the asterisk (*) represent all files in the working directory.

Is the a way to solve this problem? Thank you

0

2 Answers 2

1

The problem is that * is expanded by the shell when it's not quoted, both when you assign to ARRAY and when you echo it.

To make the shell not expand wildcards, you can use set -f. In case of the echo, you can simply double-quote the value:

$ PARAMS="key1=val1&key2=val2&key3=val3&key4=*"
$ set -f  # disable wildcard expansion
$ ARRAY=(${PARAMS//[=&]/ })
$ set +f  # restore wildcard expansion
$ echo "${ARRAY[@]}"
key1 val1 key2 val2 key3 val3 key4 *
$ echo "${#ARRAY[@]}"
8
Sign up to request clarification or add additional context in comments.

2 Comments

yes... but did you try to run echo "${ARRAY[1]}" or echo "${ARRAY[2]}"? I tried, but no output.
@vlauciani ah yes, I just forgot to remove the double-quotes that were left over from my previous version
0

Thanks to @janos approach, I found the solution:

$ PARAMS="key1=val1&key2=val2&key3=val3&key4=*"
$ set -f
$ ARRAY=(${PARAMS//[=&]/ })
$ set +f
$ echo "${ARRAY[1]}"
val1
$ echo "${ARRAY[7]}"
*
$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.