help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] ${var:?message} customization


From: Stephane Chazelas
Subject: Re: [Help-bash] ${var:?message} customization
Date: Thu, 14 May 2015 23:14:51 +0100
User-agent: Mutt/1.5.21 (2010-09-15)

2015-05-14 18:22:56 -0300, Matias A. Fonzo:
[...]
> Not really, what I have is a simple function to check if a variable is
> empty or unset (without distinction)[1] for handling positional
> parameters (arguments, options).  If I can do a simple check taking the
> approach of parameter expansion, I would avoid the function call.
> 
> [1]
> _checkArgument() {
>   if [ "$1" = "" ] ; then       # Report empty argument.
>     echo "bootstrap: '${2}' requires an argument. See 'bootstrap
>     --help'" 1>&2
>     exit 1
>   fi
> }
> 
> while [ "$1" ] ; do
>   case "$1" in
>     -s)
>       stage="$2"
>       _checkArgument "$stage" '-s'
>       shift 2
>       ;;
>     *) break;
>   esac
> done
[...]

Why not using standard getopts?

stage=default-stage
while getopts s: o
  case $o in
    (s)
      stage=$OPTARG;;
    (*)
      exit 1
  esac
done
shift "$((OPTIND - 1))"
[ -n "$stage" ] || die "stage cannot be empty"

getopts does the option parsing the standard way. That means it
will accept things like

myscript -sstage1
myscript -os stage1 # where -o is another accepted option
myscript -s -- -arg-not-not-options

It will do the error reporting (like "missing argument to -s")
by itself (though you can also do it yourself if you prefer)

-- 
Stephane




reply via email to

[Prev in Thread] Current Thread [Next in Thread]