Skip to content

Instantly share code, notes, and snippets.

@mathieu-aubin
Created February 5, 2019 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathieu-aubin/52bca3fccbdfe77498646812e58fed5e to your computer and use it in GitHub Desktop.
Save mathieu-aubin/52bca3fccbdfe77498646812e58fed5e to your computer and use it in GitHub Desktop.
url encoding and decoding in bash
#!/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