#!/bin/sh set -eu usage() { cat <<-'EOF' Usage: clamp NUMBER MIN MAX clamp -h EOF } help() { cat <<-'EOF' Options: -h, --help show this message NUMBER the number to be clamped MIN lower bound MAX upper bound Clamp the NUMBER between MIN and MAX. Examples: Assert the number is within the interval: $ clamp 5 3 9 5 When a number is below MIN it gets clamped: $ clamp 1 3 9 3 When a number is above MAX it gets clamped: $ clamp 15 3 9 9 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)) NUMBER="${1:-}" MIN="${2:-}" MAX="${3:-}" eval "$(assert-arg -- "$NUMBER" 'NUMBER')" eval "$(assert-arg -- "$MIN" 'MIN')" eval "$(assert-arg -- "$MAX" 'MAX')" if [ "$MIN" -gt "$MAX" ]; then printf 'MIN (%s) is greater then MAX (%s).\n' "$MIN" "$MAX" >&2 exit 2 fi min -- "$(max -- "$NUMBER" "$MIN")" "$MAX"