Created
February 5, 2019 00:28
-
-
Save mathieu-aubin/52bca3fccbdfe77498646812e58fed5e to your computer and use it in GitHub Desktop.
url encoding and decoding in bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
url-encode () | |
{ | |
if [[ ! -z ${2} || -z ${1} ]]; then | |
echo "error: this command needs one and only one value"; | |
echo " enclose spaces or special chars with quotes"; | |
return 1; | |
fi; | |
local string strlen encoded pos proto c o; | |
proto="$(echo ${1} | \grep --color=never :// | sed -e 's#^\(.*://\).*#\1#g')"; | |
string="${1/${proto}/}"; | |
strlen=${#string}; | |
encoded="${proto}"; | |
for ((pos=0; pos<strlen; pos++)) | |
do | |
c=${string:$pos:1}; | |
case "${c}" in | |
[-_.~a-zA-Z0-9/]) | |
o="${c}" | |
;; | |
*) | |
printf -v o '%%%02x' "'$c" | |
;; | |
esac; | |
encoded+="${o}"; | |
done; | |
REPLY="${encoded}"; | |
echo "${REPLY}" | |
} | |
url-decode () | |
{ | |
printf -v REPLY '%b' "${1//%/\\x}"; | |
echo "${REPLY}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment