hackbyte icon

convert-url.sh

hackbyte | PRO | 04/30/20 04:54:03 PM UTC | 0 ⭐ | 752 👁️ | Never ⏰ | []
Bash |

1.68 KB

|

None

|

0 👍

/

0 👎

#!/bin/bash
 
# from https://diasp.org/posts/90963a606d210138a02e047d7b62795e 2020-04-30 by zebulon 1er, dit "le maudit"
#
# usage examples:
# $ convert-url.sh
# usage: convert-url.sh [options...] URL
#
# options:
#   -d, --decode    decode URL from percents.
#   -e, --encode    encode URL to percents.
#   -h, --help      print this help and exit.
#
# arguments:
#   URL    string to convert.
#
# $ convert-url.sh -e 'https://debian.org'
# https%3A%2F%2Fdebian.org
# $ convert-url.sh -d 'https%3A%2F%2Fdebian.org'
# https://debian.org
 
PROGNAME="$(basename "$0")"
 
PrintUsage() {
  echo >&2 'usage: '"$PROGNAME"' [options...] URL'
  echo >&2
  echo >&2 'options:'
  echo >&2 '  -d, --decode    decode URL from percents.'
  echo >&2 '  -e, --encode    encode URL to percents.'
  echo >&2 '  -h, --help      print this help and exit.'
  echo >&2
  echo >&2 'arguments:'
  echo >&2 '  URL    string to convert.'
  echo >&2
}
 
URLencode() {
  # Usage: URLencode "string"
  local I LC_ALL=C
  for (( I = 0; I < ${#1}; I++ )); do
    : "${1:I:1}"
    case "$_" in
    [a-zA-Z0-9.~_-])
      printf '%s' "$_"
      ;;
 
    *)
      printf '%%%02X' "'$_"
      ;;
  esac
  done
  printf '\n'
}
 
URLdecode() {
  # Usage: URLdecode "string"
  : "${1//+/ }"
  printf '%b\n' "${_//%/\\x}"
}
 
case "$1" in
'-d' | '--decode')
  if [ -z "$2" ]; then
    echo >&2 'error : argument URL missing.'
    exit 1
  else
    URLdecode "$2"
  fi
  ;;
 
'-e' | '--encode')
  if [ -z "$2" ]; then
    echo >&2 'error : argument URL missing.'
    exit 1
  else
    URLencode "$2"
  fi
  ;;
 
'-h' | '--help')
  PrintUsage
  ;;
 
*)
  PrintUsage
  exit 1
  ;;
esac

Comments