diff options
author | EuAndreh <eu@euandre.org> | 2023-04-05 16:28:41 -0300 |
---|---|---|
committer | EuAndreh <eu@euandre.org> | 2023-04-05 16:28:41 -0300 |
commit | 36e3faf3de38d7f55797aee22bc1359da698fb39 (patch) | |
tree | 6264b6ca8e1dda92edeb4d612c6f31faf564624a | |
parent | bin/htmlesc: Fix typo in help string (diff) | |
download | dotfiles-36e3faf3de38d7f55797aee22bc1359da698fb39.tar.gz dotfiles-36e3faf3de38d7f55797aee22bc1359da698fb39.tar.xz |
bin/shesc: Add working utility
-rw-r--r-- | bin/shesc | 92 |
1 files changed, 92 insertions, 0 deletions
diff --git a/bin/shesc b/bin/shesc new file mode 100644 index 0000000..40a72b7 --- /dev/null +++ b/bin/shesc @@ -0,0 +1,92 @@ +#!/bin/sh +set -eu + + +usage() { + cat <<-'EOF' + Usage: + shesc [CONTENT...] + shesc -h + EOF +} + +help() { + cat <<-'EOF' + + Options: + -h, --help show this message + + CONTENT a literal string to be escaped + + + Convert data to/from POSIX sh double quote string escaping. If + CONTENT is not given, get data from STDIN. + + + Examples: + + Escape sh control characters in a string: + + $ printf 'content="%s"\n' "$(shesc '"string" $(dollar "`cmd`") \ ')" + content="\"string\" \$(dollar \"\`cmd\`\") \\ " + + + Escape the content from a file: + + $ shesc < file.conf + 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)) + + + +esc() { + sed 's|\([\\`"$]\)|\\\1|g' +} + + +if [ $# = 0 ]; then + esc +else + for s in "$@"; do + printf '%s\n' "$s" | esc + done +fi |