#!/bin/sh set -eu usage() { cat <<-'EOF' Usage: assert-arg -- STRING MESSAGE assert-arg -h EOF } help() { cat <<-'EOF' Options: -h, --help show this message STRING the string to check if is empty MESSAGE the message to print when STRING is empty Examples: Assert that $1 contains an argument, named FILENAME: $ eval "$(assert-arg -- "${1:-}" 'FILENAME')" EOF } for flag in "$@"; do case "$flag" in --) break ;; --help) usage help exit ;; *) ;; esac done while getopts 'h' flag; do case "$flag" in h) usage help exit ;; *) usage >&2 exit 2 ;; esac done shift $((OPTIND - 1)) STRING="${1:-}" MESSAGE="${2:-}" if [ -z "$MESSAGE" ]; then printf 'Missing MESSAGE, an argument to assert-arg.\n\n' >&2 usage >&2 exit 2 fi if [ -z "$STRING" ]; then printf 'Missing %s.\n\n' "$MESSAGE" >&2 cat <<-'EOF' usage >&2 exit 2 EOF fi