Skip to content

Instantly share code, notes, and snippets.

@bkw777
Last active August 6, 2021 18:24
Show Gist options
  • Save bkw777/83e358c8db875af45674b69939c19c3a to your computer and use it in GitHub Desktop.
Save bkw777/83e358c8db875af45674b69939c19c3a to your computer and use it in GitHub Desktop.
urlencode urldecode in pure bash as efficient as possible
#!/bin/bash
# urlencode / urldecode in pure bash without externals
# no backticks or forking, all in-memory ops
# urlencode/urldecode the contents of $x, place results back in $x
# allow bash-isms
# b.kenyon.w@gmail.com
urlencx () {
local LANG=C i b t=$x l=${#x} ;x=''
for ((i=0;i<l;i++)); do
b=${t:i:1}
[[ "$b" =~ [a-zA-Z0-9\.\~\_\-] ]] || printf -v b '%%%02X' "'$b"
x+=$b
done
}
urldecx () {
local LANG=C
x="${x//+/ }"
printf -v x '%b' "${x//%/\\x}"
}
printf -v x "This'll be fun\!\n*Won't* \"it\"?"
printf 'original: x="%s"\n' "$x"
urlencx
printf ' encoded: x="%s"\n' "$x"
urldecx
printf ' decoded: x="%s"\n' "$x"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment