#!/bin/sh set -eu usage() { cat <<-'EOF' Usage: htmlesc [-e|d] htmlesc -h EOF } help() { cat <<-'EOF' Options: -e escape the string (the default action) -d unescape (de-escape?) the string -h, --help show this message Get a string from STDIN and convert it to/from HTML escaping. Examples: oij $ printf 'a > 5 && !b' | htmlesc a > 5 && !b Unescape the content from a file: $ htmlesc -d < file.html EOF } for flag in "$@"; do case "$flag" in --) break ;; --help) usage help exit ;; *) ;; esac done ENCODE=false DECODE=false while getopts 'edh' flag; do case "$flag" in e) ENCODE=true ;; d) DECODE=true ;; h) usage help exit ;; *) usage >&2 exit 2 ;; esac done shift $((OPTIND - 1)) if [ "$ENCODE" = true ] && [ "$DECODE" = true ]; then printf 'Both -e and -d given. Pick one.\n' >&2 usage >&2 exit 2 elif [ "$DECODE" = true ]; then sed \ -e 's|&|\&|g' \ -e 's|<|<|g' \ -e 's|>|>|g' \ -e 's|"|"|g' \ -e "s|'|'|g" else sed \ -e 's|&|\&|g' \ -e 's|<|\<|g' \ -e 's|>|\>|g' \ -e 's|"|\"|g' \ -e "s|'|\'|g" fi