Skip to content

Instantly share code, notes, and snippets.

@ernstki
Last active November 23, 2024 18:20
Show Gist options
  • Save ernstki/8db533a825f0d06b8200136832284d22 to your computer and use it in GitHub Desktop.
Save ernstki/8db533a825f0d06b8200136832284d22 to your computer and use it in GitHub Desktop.
Bash function to separate "cuddled" options like '-nvalue' or '--name=value'

"Uncuddle" arguments like -pVALUE, or --param=VALUE

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 the while (( $# )) 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment