#!/bin/bash function check_arg(){ if [[ $2 == -* ]]; then echo "Option $1 requires an argument" >&2 exit 1 fi } function parse_param() { if [ -z "$1" ];then echo "Empty list of options" >&2 exit 1 fi while getopts ":np:" opt; do case $opt in p) check_arg "-p" "$OPTARG" echo "-p(param) was triggered, Parameter: '$OPTARG'" ;; n) echo "-n(no param) was triggered" ;; \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; :) echo "Option -$OPTARG requires an argument (getopts)" >&2 exit 1 ;; esac done } parse_param "$@"
[bash]$ ./test.sh Empty list of option [bash]$ ./test.sh -m Invalid option: -m [bash]$ ./test.sh -n -n(no param) was triggered [bash]$ ./test.sh -n -p -n(no param) was triggered Option -p requires an argument (getopts) [bash]$ ./test.sh -p -n Option -p requires an argument [bash]$ ./test.sh -p"1 2 3" -p(param) was triggered, Parameter: '1 2 3'
parse_param $1 $2 $3 parse_param "$1" "$2" "$3"
[bash]$ ./test.sh -p"1 2 3"
:) echo "Option -$OPTARG requires an argument (getopts)" >&2 exit 1 ;;
parse_param "$@"
:) echo "Option -$OPTARG requires an argument (getopts)" >&2 exit 1 ;;
function check_arg(){ if [[ $2 == -* ]]; then echo "Option $1 requires an argument" >&2 exit 1 fi }
check_arg "-p" "$OPTARG"
[bash]$ ./test.sh -p -n
\?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;;
Source: https://habr.com/ru/post/169133/