Bash Snippet: URL Encoding

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:

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//</%3c}   ; i=${i//=/%3d}
        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..."
This entry was posted in Bash. Bookmark the permalink.

4 Responses to Bash Snippet: URL Encoding

  1. Michael says:

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

  2. Esteban says:

    You are my hero 🙂

  3. Mariusz says:

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

  4. Chris says:

    @Mariusz: A while ago Debian (and by extension Raspbian and Ubuntu) changed the symlink for #!/bin/sh from bash to dash (the Debian Almquist shell). Try specifying the bash shell in your shebang:

    #!/bin/bash

Leave a Reply

Your email address will not be published. Required fields are marked *