Search code examples
bashpositional-operator

Bash: handling mass arguments


I'd like to be able to handle multiple arguments to a given flag no matter what the order of flags is. Do you guys think this is acceptable? Any improvements?

So:

$ ./script -c opt1 opt2 opt3 -b foo

opt1 opt2 opt3
foo

Code:

echo_args () {
    echo "$@"
}


while (( $# > 0 )); do
    case "$1" in
        -b)
            echo $2
        ;;

        -c|--create)
            c_args=()

            # start looping from this flag
            for arg in ${@:2}; do
                [ "${arg:0:1}" == "-" ] && break
                c_args+=("$arg")
            done

            echo_args "${c_args[@]}"
        ;;

        *)
            echo "huh?"
        ;;
    esac

    shift 1
done

Solution

  • The getopts utility shall retrieve options and option-arguments from a list of parameters.

    $ cat script.sh
    
    cflag=
    bflag=
    while getopts c:b: name
    do
        case $name in
        b)    bflag=1
              bval="$OPTARG";;
        c)    cflag=1
              cval="$OPTARG";;
        ?)   printf "Usage: %s: [-c value] [-b value] args\n" $0
              exit 2;;
        esac
    done
    if [ ! -z "$bflag" ]; then
        printf 'Option -b "%s" specified\n' "$bval"
    fi
    if [ ! -z "$cflag" ]; then
        printf 'Option -c "%s" specified\n' "$cval"
    fi
    shift $(($OPTIND - 1))
    printf "Remaining arguments are: %s\n" "$*"
    

    Note the Guideline 8: When multiple option-arguments are specified to follow a single option, they should be presented as a single argument, using commas within that argument or <blank>s within that argument to separate them.

    $ ./script.sh -c "opt1 opt2 opt3" -b foo
    
    Option -b "foo" specified
    Option -c "opt1 opt2 opt3" specified
    Remaining arguments are:
    

    The standard links are listed below: