One approach would be to encode everything, but the approach I took was to just encode things I thought might be problematic to pass over the query string.

URL (a.k.a percent) encoding of a string in bash:

[cc lang=”bash” theme=”blackboard” width=”100%”]

urlencode () {
tab=”`echo -en “\x9″`”
i=”$@”
i=${i//%/%25} ; i=${i//’ ‘/%20} ; i=${i//$tab/%09}
i=${i//!/%21} ; i=${i//'”‘/%22} ; i=${i//#/%23}
i=${i//\$/%24} ; i=${i//\&/%26} ; i=${i//\’/%27}
i=${i//(/%28} ; i=${i//)/%29} ; i=${i//\*/%2a}
i=${i//+/%2b} ; i=${i//,/%2c} ; i=${i//-/%2d}
i=${i//\./%2e} ; i=${i//\//%2f} ; i=${i//:/%3a}
i=${i//;/%3b} ; i=${i///%3e} ; i=${i//\?/%3f} ; i=${i//@/%40}
i=${i//\[/%5b} ; i=${i//\\/%5c} ; i=${i//\]/%5d}
i=${i//\^/%5e} ; i=${i//_/%5f} ; i=${i//\`/%60}
i=${i//\{/%7b} ; i=${i//|/%7c} ; i=${i//\}/%7d}
i=${i//\~/%7e}
echo “$i”
i=””
}

urlencode “The sun is hot, 42 / 0 = undefined, & 1 + 1 = 2…”

[/cc]

Categories:Bash
Published on :Posted on

4 thoughts on “Bash Snippet: URL Encoding”

·

Best way to do this I’ve seen yet. Many thanks.

·

You are my hero 🙂

·

root@raspberrypi:/home/pi/scripts# ./urlencode.sh
./urlencode.sh: 6: ./urlencode.sh: Bad substitution

Post your comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.