Last active
January 28, 2022 06:34
-
-
Save kugland/ca1017984badc23b43cbeecfd828dce2 to your computer and use it in GitHub Desktop.
urlencode / urldecode as a shell script
This file contains hidden or 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 | |
SCRIPT_NAME="$(basename "$0")" | |
if [ "$SCRIPT_NAME" != "urlencode" ] && [ "$SCRIPT_NAME" != "urldecode" ]; then | |
echo 'Please run this script as "urlencode" or "urldecode"' | |
exit 1 | |
fi | |
if [ $# -lt 1 ]; then | |
echo "Usage: $SCRIPT_NAME <url>" | |
exit 1 | |
fi | |
case "$SCRIPT_NAME" in | |
urlencode) | |
test -x /usr/bin/python3 \ | |
&& exec /usr/bin/python3 -c "import sys; import urllib.parse as up; print(up.quote_plus(sys.argv[1]))" "$1" | |
test -x /usr/bin/python2 \ | |
&& exec /usr/bin/python2 -c "import sys; import urllib as ul; print ul.quote_plus(sys.argv[1])" "$1" | |
test -x /usr/bin/ruby \ | |
&& exec /usr/bin/ruby -r cgi -e "puts CGI.escape(ARGV[0])" "$1" | |
test -x /usr/bin/php \ | |
&& exec /usr/bin/php -r 'echo rawurlencode($argv[1]), "\n";' "$1" | |
test -x /usr/bin/perl && /usr/bin/perl -MURI::Escape -e 1 >/dev/null 2>&1 \ | |
&& exec /usr/bin/perl -MURI::Escape -e 'print uri_escape($ARGV[0]), "\n";' -- "$1"; | |
test -x /usr/bin/node \ | |
&& exec /usr/bin/node -e "console.log(encodeURIComponent(process.argv[1]))" "$1" | |
;; | |
urldecode) | |
test -x /usr/bin/python3 \ | |
&& exec /usr/bin/python3 -c "import sys; import urllib.parse as up; print(up.unquote_plus(sys.argv[1]))" "$1" | |
test -x /usr/bin/python2 \ | |
&& exec /usr/bin/python2 -c "import sys; import urllib as ul; print ul.unquote_plus(sys.argv[1])" "$1" | |
test -x /usr/bin/ruby \ | |
&& exec /usr/bin/ruby -r cgi -e "puts CGI.unescape(ARGV[0])" "$1" | |
test -x /usr/bin/php \ | |
&& exec /usr/bin/php -r 'echo rawurldecode($argv[1]), "\n";' "$1" | |
test -x /usr/bin/perl && /usr/bin/perl -MURI::Escape -e 1 >/dev/null 2>&1 \ | |
&& exec /usr/bin/perl -MURI::Escape -e 'print uri_unescape($ARGV[0]), "\n";' -- "$1"; | |
test -x /usr/bin/node \ | |
&& exec /usr/bin/node -e "console.log(decodeURIComponent(process.argv[1]))" "$1" | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment