3

I have this Bash script:

#!/bin/bash

rawurldecode() {

  # This is perhaps a risky gambit, but since all escape characters must be
  # encoded, we can replace %NN with \xNN and pass the lot to printf -b, which
  # will decode hex for us

  printf -v REPLY '%b' "${1//%/\\x}" # You can either set a return variable (FASTER)

  echo "${REPLY}"  #+or echo the result (EASIER)... or both... :p
}

echo -e "Content-type: video/x-matroska\n"

arr=(${QUERY_STRING//=/ })
ffmpeg -i "$(rawurldecode ${arr[1]})" -acodec copy -vcodec copy -map 0:0 -map 0:2 -f matroska - 2>/dev/null &
pid=$!
trap "kill $pid" SIGTERM SIGPIPE
wait

I want to change it so it can handle multiple parameters in the query string like this:

param1=value1&param2=value2&param3=value3

currently the arr regex split is based on = so it can only handle one parameter. I am not sure how to change this regex so I get arr[1] = value1; arr[2] = value2, etc.
Ideally I need it to be an associative array like: arr['param1'] = value1 but I am not sure if this is possible in Bash.

Solutions in other languages (PHP, Perl, Python) are acceptable as long as the behaviour of the script remains the same (i.e. it needs to take the query string and output the header + output from the stdout, and be able to kill the process it spawned when the client disconnects).

Any suggestions how to sanitize this input are also welcome.

1 Answer 1

1

You can just change the line:

arr=(${QUERY_STRING//=/ })

With:

arr=(${QUERY_STRING//[=&]/ })

Then you can get your values in the odd indexes.

Example

$ QUERY_STRING='param1=value1&param2=value2&param3=value3'
$ arr=(${QUERY_STRING//[=&]/ })
$ echo ${arr[1]}
value1
$ echo ${arr[3]}
value2
$ echo ${arr[5]}
value3

Reading your question again, I see you want the values in subsequent indices. You can do that with the extglob shell option as follows:

shopt -s extglob # with this you enable 'extglob'
arr=${QUERY_STRING//?(&)+([^&=])=/ }

Explanation:

?(&) -> matches zero or one occurrence of &
+([^&=])= -> matches 1+ occurrences of string without & or = followed by a =

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Any comments on sanitization are welcome (i.e. how to make sure value1, value2, etc. don't include a character that would allow executing random commands).
thanks! this even works for the whole URL with parameters, if you include ? inside [], the main URL becomes arr[0], first key arr[1] and first value arr[2] and so on! Nice!

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.