urlencoderΒΆ

Updated: Apr 22, 2023

Hi friends,

Previously I had a post regarding url encoding and decoding, This is much improved version of that script. To know more about urlencoding, try this link

#!/bin/bash
# urlencode - program to urlencode/urldecode
# Author: Mohan Raman
# License: Its in public domain.

USAGE="[USAGE]
     urlencode [-e|-d] [-h]
"

HELP="${USAGE}
[DESCRIPTION]
     -e      URLEncode standard input(default)
     -d      URLDecode standard input

[EXAMPLE]
     $ urlencode
     http://www.google.co.in
     http%3A%2F%2Fwww.google.co.in

     $ urlencode -d
     http%3A%2F%2Fwww.google.co.in
     http://www.google.co.in
"

encode()
{
sed -e's/./&\n/g' -e's/ /%20/g' | grep -v '^$' | while read CHAR; do test "${CHAR}" = "%20" && echo "${CHAR}" || echo "${CHAR}" | grep -E '[-[:alnum:]!*.'"'"'()]|\[|\]' || echo -n "${CHAR}" | od -t x1 | tr ' ' '\n' | grep '^[[:alnum:]]\{2\}$' | tr '[a-z]' '[A-Z]' | sed -e's/^/%/g'; done | sed -e's/%20/+/g' | tr -d '\n'; echo
}

decode()
{
sed -n -e's/%\([0-9A-F][0-9A-F]\)/\\x\1/g' -e's/+/ /g' -e's/.*/echo -e "&"/g' -ep | "${SHELL}"
}

DECODE="0"

while getopts "edh" OPTION
do
     case "${OPTION}" in
     d) DECODE="1";;
     h) echo "${HELP}"; exit 0;;
     \?) echo "${USAGE}"; exit 1;;
     esac
done

test "${DECODE}" = "0" && encode
test "${DECODE}" = "1" && decode