hackbyte

convert-url.sh

Apr 30th, 2020
780
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.68 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # from https://diasp.org/posts/90963a606d210138a02e047d7b62795e 2020-04-30 by zebulon 1er, dit "le maudit"
  4. #
  5. # usage examples:
  6. # $ convert-url.sh
  7. # usage: convert-url.sh [options...] URL
  8. #
  9. # options:
  10. #   -d, --decode    decode URL from percents.
  11. #   -e, --encode    encode URL to percents.
  12. #   -h, --help      print this help and exit.
  13. #
  14. # arguments:
  15. #   URL    string to convert.
  16. #
  17. # $ convert-url.sh -e 'https://debian.org'
  18. # https%3A%2F%2Fdebian.org
  19. # $ convert-url.sh -d 'https%3A%2F%2Fdebian.org'
  20. # https://debian.org
  21.  
  22. PROGNAME="$(basename "$0")"
  23.  
  24. PrintUsage() {
  25.   echo >&2 'usage: '"$PROGNAME"' [options...] URL'
  26.   echo >&2
  27.   echo >&2 'options:'
  28.   echo >&2 '  -d, --decode    decode URL from percents.'
  29.   echo >&2 '  -e, --encode    encode URL to percents.'
  30.   echo >&2 '  -h, --help      print this help and exit.'
  31.   echo >&2
  32.   echo >&2 'arguments:'
  33.   echo >&2 '  URL    string to convert.'
  34.   echo >&2
  35. }
  36.  
  37. URLencode() {
  38.   # Usage: URLencode "string"
  39.   local I LC_ALL=C
  40.   for (( I = 0; I < ${#1}; I++ )); do
  41.     : "${1:I:1}"
  42.     case "$_" in
  43.     [a-zA-Z0-9.~_-])
  44.       printf '%s' "$_"
  45.       ;;
  46.  
  47.     *)
  48.       printf '%%%02X' "'$_"
  49.       ;;
  50.   esac
  51.   done
  52.   printf '\n'
  53. }
  54.  
  55. URLdecode() {
  56.   # Usage: URLdecode "string"
  57.   : "${1//+/ }"
  58.   printf '%b\n' "${_//%/\\x}"
  59. }
  60.  
  61. case "$1" in
  62. '-d' | '--decode')
  63.   if [ -z "$2" ]; then
  64.     echo >&2 'error : argument URL missing.'
  65.     exit 1
  66.   else
  67.     URLdecode "$2"
  68.   fi
  69.   ;;
  70.  
  71. '-e' | '--encode')
  72.   if [ -z "$2" ]; then
  73.     echo >&2 'error : argument URL missing.'
  74.     exit 1
  75.   else
  76.     URLencode "$2"
  77.   fi
  78.   ;;
  79.  
  80. '-h' | '--help')
  81.   PrintUsage
  82.   ;;
  83.  
  84. *)
  85.   PrintUsage
  86.   exit 1
  87.   ;;
  88. esac
Advertisement
Add Comment
Please, Sign In to add comment