Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

url-encode in a shell script

If you need to transform a string into a url-encoded format and you want to avoid bash, here is my adaptation of a fantastic unix.com post.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/sh
# Author: Chubler_XL
# Converted to dash from bash version at https://www.unix.com/shell-programming-and-scripting/277083-url-encoding-string-using-sed.html

url_var() {
   LC_ALL=C
   ___encoded=""
   ___temp="$( mktemp )"
   # needs GNU head
   echo "${1}" | sed -r -e 's/(.)/\1\n/g;' | head -n -1 | while read char ;
   do
      #echo "Char: ${char}"
      test '\0' != "${char}" &&
      case "${char}" in
         [a-zA-Z0-9/_.~-] ) ___encoded="${___encoded}${char}" ; test -n "${DEBUG}" && echo "Found simple \"${char}\"" 1>&2 ;;
         * ) ___encoded="${___encoded}$( $( which printf ) "%%%02x" "'${char}" )" ;;
      esac
      echo "${___encoded}" > "${___temp}"
   done
   ___encoded="$( cat "${___temp}" )" ; rm -f "${___temp}"
   echo "${___encoded}"
}

url_var "${1}"

I intend to add this to my bgscripts package at some point, as url-encode.

Comments