Skip to content

Instantly share code, notes, and snippets.

@duksis
Created October 15, 2012 07:22
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save duksis/3891185 to your computer and use it in GitHub Desktop.
Save duksis/3891185 to your computer and use it in GitHub Desktop.
URL encoding in bash
#!/bin/bash
function urlencode() {
echo -n "$1" | perl -MURI::Escape -ne 'print uri_escape($_)'
}
#!/bin/bash
## borrowed from http://blog.famzah.net/2011/08/25/url-escape-in-bash/
## Original file http://www.famzah.net/download/bash_urlencode/escape.sh.txt
set -u
declare -A ord_hash # associative hash; requires Bash version 4
function init_urlencode() {
# this is the whole ASCII set, without the chr(0) and chr(255) characters
ASCII='
 !"#$%&'\''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ'
# chr(0) cannot be stored in a Bash variable
local idx
for idx in {0..253}; do # 0..253 = 254 elements = length($ASCII)
local c="${ASCII:$idx:1}" # VERY SLOW
local store_idx=$(($idx+1))
ord_hash["$c"]="$store_idx"
# chr(255) cannot be used as a key
done
}
function urlencode() {
local inp="$1"
local len="${#inp}"
local n=0
local val
while [ "$n" -lt "$len" ]; do
local c="${inp:$n:1}" # VERY SLOW
if [ "$c" == "ÿ" ]; then # chr(255) cannot be used as a key
val=255
else
val="${ord_hash[$c]}"
fi
printf '%%%02X' "$val"
n=$((n+1))
done
}
init_urlencode # call only once
urlencode 'some^fancy#text'
@jjosserand
Copy link

Nice. Love the perl solution.
What about decoding?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment