How to define a shell script with variable number of arguments?

后端 未结 3 559
栀梦
栀梦 2020-12-08 02:22

I would like to define a simple abbreviation of a call to gs (ghostscript) via a shell script. The first argument(s) give all the files that should be merged, t

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 03:13

    To pass the output file as the last argument, use an array:

    ARGS=("$@")
    # Get the last argument
    outputfile=${ARGS[-1]}
    # Drop it from the array
    unset ARGS[${#ARGS[@]}-1]
    
    exec gs ... -sOUTPUTFILE=$outputfile "${ARGS[@]}"
    

    Before version 4, bash didn't allow negative subscripts in arrays (and produced the error reported by Marius in the comments), so if you're using 3.x you need to use the much uglier

    outputfile=${ARGS[${#ARGS[@]}-1]}
    

    This works for bash 4.x as well.

提交回复
热议问题