Tagged: urlencode

Unix: Urlencode and urldecode from the command line with Perl

If you want to urlencode or urldecode from the command line–that is escape or unescape URL content–the simplest solution is to use Perl:

perl -MURI::Escape -e 'print uri_escape("&");'

Use the same command, but with url_unescape to reverse the process.

unix urlencode

Unix: Urlencode decode from the command line with bash

If you want a native bash solution to urlencode and urldecode, put this in your .bashrc

urlencode() {
    # urlencode <string>

    local length="${#1}"
    for (( i = 0; i < length; i++ )); do
        local c="${1:i:1}"
        case $c in
            [a-zA-Z0-9.~_-]) printf "$c" ;;
            *) printf '%s' "$c" | xxd -p -c1 |
                   while read c; do printf '%%%s' "$c"; done ;;

urldecode() {
    # urldecode <string>

    local url_encoded="${1//+/ }"
    printf '%b' "${url_encoded//%/\\x}"

If you want to use this from xargs, you’ll need to export the function via:

export -f urlencode
unix urlencode urldecode

Page 1 of 1