Created
June 11, 2020 19:14
-
-
Save cideM/ab87ebcbe43ec1488be255c2bcacd945 to your computer and use it in GitHub Desktop.
URL Encode a String with POSIX Shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# https://en.wikipedia.org/wiki/Percent-encoding | |
# https://stackoverflow.com/questions/38015239/url-encoding-a-string-in-shell-script-in-a-portable-way | |
# https://www.gnu.org/software/gettext/manual/html_node/The-LANGUAGE-variable.html#The-LANGUAGE-variable | |
# "The variable LANGUAGE is ignored if the locale is set to ‘C’" | |
# Not entirely sure why this is done to be honest | |
LANG=C; | |
while IFS= read -r c; | |
do | |
case "$c" in | |
# Continue on non-reserved characters | |
[a-zA-Z0-9.~_-]) | |
printf "$c" | |
continue | |
;; | |
esac | |
# Don't do 'printf "$c"' since it breaks on '%' as input | |
printf '%s' "$c" | od -An -tx1 | tr ' ' % | tr -d '\n' | |
done <<EOF | |
$(fold -w1) | |
EOF | |
# ^ This reads one character at a time by setting the column width to 1. | |
# Meaning THIS will be wrapped to: | |
# T | |
# H | |
# I | |
# S | |
# This is really clever but also really hacky |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment