parse arguments after getopts

22,954

Solution 1

You can do something like:

shift $(($OPTIND - 1))
first_arg=$1
second_arg=$2

after the loop has run.

Solution 2

To capture all the remaining parameters after the getopts processing, a good solution is to shift (remove) all the processed parameters (variable $OPTIND) and assign the remaining parameters ($@) to a specific variable. Short answer:

shift $(($OPTIND - 1))
remaining_args="$@"

Long example:

#!/bin/bash

verbose=false

function usage () {
    cat <<EOUSAGE
$(basename $0) hvr:e:
    show usage
EOUSAGE
}

while getopts :hvr:e: opt
do
    case $opt in
        v)
            verbose=true
            ;;
        e)
            option_e="$OPTARG"
            ;;
        r)
            option_r="$option_r $OPTARG"
            ;;
        h)
            usage
            exit 1
            ;;
        *)
            echo "Invalid option: -$OPTARG" >&2
            usage
            exit 2
            ;;
    esac
done


echo "Verbose is $verbose"
echo "option_e is \"$option_e\""
echo "option_r is \"$option_r\""
echo "\$@ pre shift is \"$@\""
shift $((OPTIND - 1))
echo "\$@ post shift is \"$@\""

This will output

$ ./test-getopts.sh -r foo1 -v -e bla -r foo2 remain1 remain2
Verbose is true
option_e is "bla"
option_r is " foo1 foo2"
$@ pre shift is "-r foo1 -v -e bla -r foo2 remain1 remain2"
$@ post shift is "remain1 remain2"
Share:
22,954
speendo
Author by

speendo

Updated on October 09, 2020

Comments

  • speendo
    speendo over 3 years

    I want to call a bash script like this

    $ ./scriptName -o -p -t something path/to/file
    

    This is as far as I get

    #!/bin/bash
    
    o=false
    p=false
    
    while getopts ":opt:" options
    do
        case $options in
            o ) opt1=true
            ;;
            p ) opt2=true
            ;;
            t ) opt3=$OPTARG
            ;;
        esac
    done
    

    but how do I get the path/to/file?

  • Armand
    Armand over 9 years
    Could the first line be written shift $((OPTIND - 1)) - i.e. losing the dollar sign inside the parentheses?
  • c-garcia
    c-garcia over 7 years
    Armand, so it seems as per: tldp.org/LDP/abs/html/arithexp.html