ssh — guest: ~ connected
guest@ludovic.toinel.com:~$ man urlencode

urlencode — percent-encode text for a URL, or decode it

SYNOPSIS

urlencode [-d] [-f] <text...> urlencode [-d] [-f] (read piped input, line by line)

DESCRIPTION

Encodes its argument so it can travel safely inside a URL: every character that is not a letter, a digit or one of - _ . ~ is replaced by a percent sign and the hexadecimal value of its UTF-8 bytes. With -d it does the reverse. Piped input is processed one line at a time, so a list stays a list.

Decoding malformed text (a lone %, an invalid UTF-8 sequence) reports where the problem is instead of guessing.

OPTIONS

-d decode instead of encoding (same as the urldecode command) -f form mode (application/x-www-form-urlencoded): a space is written, and read back, as a plus sign -- end of options (for a text starting with a dash)

HOW IT WORKS

A URL may only contain a small set of ASCII characters, and several of them have a job: ? starts the query string, & separates parameters, = splits a name from its value, # starts the fragment, / separates path segments. Percent-encoding (RFC 3986) lets a value carry those characters, spaces and non-ASCII text without being mistaken for URL syntax: the text is converted to UTF-8 and each unsafe byte becomes %XX. A space is %20, & is %26, é is %C3%A9.

This command encodes a component — a parameter value, a path segment — so it also escapes : / ? & = and the sub-delimiters ! ' ( ) *. Do not run it on a whole URL: encode each value, then assemble the URL.

HTML forms use a variant in which a space becomes + (and a real plus sign becomes %2B): that is the -f mode. Everything happens in your browser.

USE CASES

  • build a query string by hand: ?q= followed by the encoded search terms;
  • read a redirect or callback URL found in a log, with urlencode -d;
  • pass a URL as a parameter of another URL (OAuth redirect_uri);
  • encode a list of values in one go: cat names.txt | urlencode.

EXAMPLES

urlencode "hello world & more" urlencode -f "a b+c" urlencode -d caf%C3%A9%20%26%20th%C3%A9 echo "a/b?c=d" | urlencode

SEE ALSO

urldecode, base64, json, qr