#!/bin/sh set -eu usage() { cat <<-'EOF' Usage: htmlesc [-e|d] [CONTENT...] 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 CONTENT a literal string to be escaped Convert data to/from HTML escaping. If CONTENT is not given, get data from STDIN. Examples: Escape HTML control characters in a string: $ htmlesc 'a > 5 && !b' 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 fi decode() { sed \ -e 's|&|\&|g' \ -e 's|<|<|g' \ -e 's|>|>|g' \ -e 's|"|"|g' \ -e "s|'|'|g" } encode() { sed \ -e 's|&|\&|g' \ -e 's|<|\<|g' \ -e 's|>|\>|g' \ -e 's|"|\"|g' \ -e "s|'|\'|g" } if [ "$DECODE" = true ]; then FN=decode else FN=encode fi if [ $# = 0 ]; then "$FN" else for s in "$@"; do printf '%s\n' "$s" | "$FN" done fi