Encoding/Decoding Strings for URLs in ZSH
Posted by Chad Humphries over 2 years ago
These functions encode or decode a string given as argument to be used in URLs, which means characters are encoded to %FF strings and back. Requires option extendedglob to be set.

function url-encode { E=${${(j: :)@}//(#b)(?)/%$[[##16]##${match[1]}]} }
function url-decode { D=${1//\%(#b)([0-F][0-F])/\\\x$match[1]} }

# Example:
$ url-encode "This needs to be escaped."
$ echo $E
%54%68%69%73%20%6E%65%65%64%73%20%74%6F%20%62%65%20%65%73%63%61%70%65%64%2E
$ url-decode $E
$ echo $D
This needs to be escaped.
$ URL="http://www.my-cgi-page.com/index.pl?q=$E"
Language Shell/Scripting / Tagged with zsh