urlencoder

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, http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

#!/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

Download: urlencoder

Advertisements

3 thoughts on “urlencoder

  1. LOL i was solving this problem in my minimalistic BASH webserver and i’ve found bit more simple way:
    urldecode() { echo -e $( echo “$@” | sed -e ‘s/+/ /g;s/%/\\x/g’ ); }
    i also think that any string can be encoded using much shorter code…
    hope it will help ;)

    • Thanks for the shortest one. I always believe If somebody able to understand a code, they always come up with a much simplest one. I’m happy that someone other than me can able to understand my script :).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s