3

I'm trying to decode GET arguments in pure bash.

I.e.: hello+%26+world should become hello & world

So far I've managed to get this:

#!/usr/bin/sh
echo "Content-type: text/plain"
echo ""

CMD=`echo "$QUERY_STRING" | grep -oE "(^|[?&])cmd=[^&]+" | sed "s/%20/ /g" | cut -f 2 -d "="`
CMD="${CMD//+/ }"

echo $CMD

which replaces all the + with a space.

Is there a better way to do this? Or do I just have to look for each possible encoded special character and replace it?

1 Answer 1

10

You can use this function for URL decoding:

decodeURL() { printf "%b\n" "$(sed 's/+/ /g; s/%\([0-9a-f][0-9a-f]\)/\\x\1/g;')"; }

Then test it as:

decodeURL <<< 'hello+%26+world'
hello & world

Explanation:

  • printf %b - expands backslash escape sequences in the corresponding argument
  • s/+/ /g - Replace each + by a space
  • s/%\([0-9a-f][0-9a-f]\)/\\x\1/g - Replace each % followed by 2 hex characters by literal \x and same hex characters so that printf can print equivalent ASCII character for it
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, that seems to work, but how can I execute this? The string returned is a command like ls -al that I would like to execute and print the results
I had to match on the capital hex characters as well: s/%\([0-9a-fA-F][0-9a-fA-F]\)/\\x\1/g
Yes that's right @angerelle. gnu sed also supports /i mode for ignore case matching.
Here is an example in a script where I assign the result to a variable. I had to add an extra \\ before the x . The example is taking parameter 3 in a shell script file . export DECODE_URL=`printf "%b\n" "$(echo $3 | sed 's/+/ /g; s/%\([0-9a-fA-F][0-9a-fA-F]\)/\\\\x\1/g;')"` `
I'd remove the \n if I were you. Don't alter the input, it is not your call to make. Also, the [...] stuff is unnecessary, since URL encoding requires % to be %%-encoded as well.

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.