#!/bin/bash # colorize-url - apply ANSI colors to URL components # # Usage: # colorize-url # colorize-url -h # # Parses a URL into protocol, hostname, path, query parameters, and fragment, # then prints it with each component in a distinct color for readability # Query string keys and values are colored separately _colorize_url() ( local SCRIPT_NAME; SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")" case "${BASH_SOURCE[0]}" in /dev/*|/proc/*) SCRIPT_NAME="" ;; esac case "$SCRIPT_NAME" in ""|bash|sh|zsh|dash) SCRIPT_NAME="colorize-url" ;; esac #/# Internal Functions #\# # Prints the nonprinting character for the requested ANSI color _color() { local base=30 # regular colors start here local bright_base=90 # bright (bold in some terminals) colors start here # Get starting value based on whether or not bright variant was requested if [ "$1" = 'bright' ]; then local color_code=$bright_base && shift else local color_code=$base fi # Convert color name to ANSI offset local offset case "$1" in black) offset=0 ;; red) offset=1 ;; green) offset=2 ;; yellow) offset=3 ;; blue) offset=4 ;; magenta) offset=5 ;; cyan) offset=6 ;; white) offset=7 ;; reset) printf '\033[m'; return 0 ;; # reset to terminal default *) _error "Invalid color '$1'"; return 1 ;; esac color_code=$((color_code + offset)) printf '\033[%sm' "$color_code" } # Returns 0 if $1 contains $2 _contains() { local string="$1" local substring="$2" # If string contains substring, it will be deleted and the two strings will no longer match [ "${string#*"$substring"}" != "$string" ] } _error() { echo "[ERR][$SCRIPT_NAME] $*" >&2; } # Clean up internal functions when finished #\# Internal Functions #/# _show_help() { local s; [ -t 1 ] && s=$'\033[4m' local r; [ -t 1 ] && r=$'\033[24m' cat < ?k1=v1&k2=v2) query="$c_question?${colorized_query#"$c_and&"}" # leading "?" fi # Colorize path components and slashes if [ "$has_path" ]; then local colorized_slash="$c_slash/$c_path" path="$colorized_slash${path//"/"/"$colorized_slash"}" fi # Finish colorizing and reassemble URL local colorized_url="$c_protocol${protocol}://$c_hostname${hostname}${path}${query}${c_hash}${hash}$c_reset" echo "$colorized_url" ) _colorize_url "$@" __colorize_url_rc=$? unset -f _colorize_url if [ -n "${BASH_SOURCE[0]}" ] && [ "${BASH_SOURCE[0]}" != "$0" ]; then eval "unset __colorize_url_rc; return $__colorize_url_rc" fi eval "unset __colorize_url_rc; exit $__colorize_url_rc"