Here's a Bash function that will separate option-value pairs where the option and value are glued together without an intervening space.
You give it:
- a bunch of possible prefixes as arguments, like
-p
,--param=
, and--parameter=
- and as the last argument, the maybe-option-value-pair to be checked (
$1
in thewhile (( $# ))
loop below)
and it returns the VALUE
part, or the empty string if there was no VALUE
part (the option and argument were separate).
# return value cuddled option/value pair given as the last given
# argument returns empty string if the last argument is NOT cuddled;
# test this in the calling subprogram and 'shift' the next argument if
# necessary
#
# $1 .. ${n-1} possible argument prefixes, like '-p', '--param='
# $n the argument to be parsed
uncuddle() {
(( ${TRACE:-} )) && set -x
# all but the last argument
local opts=( ${@:1:$(($#-1))} )
# the input parameter, might look like '--name=VALUE' or '-pVALUE'
local input=${@: -1}
local value=
for opt in "${opts[@]}"; do
[[ $input =~ ^$opt. ]] && value=${input#$opt}
done
echo "$value"
set -
}
Use it like this:
while (( $# )); do
case "$1" in
-s*|--suf*)
suffix=$( uncuddle -s --suff= --suffix= "$1" )
# 'uncuddle' returns empty string if no "cuddled" option found
if [[ -z $suffix ]]; then
shift
suffix=$1
fi
;;
# ⋮
esac
done