Skip to content

Instantly share code, notes, and snippets.

@Tantas
Forked from cdown/gist:1163649
Last active August 29, 2015 14:04
Show Gist options
  • Save Tantas/5412d1e319c69d0d56ab to your computer and use it in GitHub Desktop.
Save Tantas/5412d1e319c69d0d56ab to your computer and use it in GitHub Desktop.
Pure Bash Implementation of URL Decode
stripEncodedLineEndings() {
# stripEncodedLineEndings <string>
local stripFirstPart="${1//%0D}"
echo "${stripFirstPart//%0A}"
}
urlencode() {
# urlencode <string>
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf "$c" ;;
*) printf '%%%02X' "'$c"
esac
done
}
urldecode() {
# urldecode <string>
local stripedOfLineTerminators=$(stripEncodedLineEndings $1)
local url_encoded="${stripedOfLineTerminators//+/ }"
printf '%b' "${url_encoded//%/\x}"
}
@Tantas
Copy link
Author

Tantas commented Jul 19, 2014

The Gist that this was forked from failed to output a correct urldecoded string if the input string contained encoded line terminators. This solves the problem by removing line terminators from the encoded string before decoding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment