Search code examples
bashshellshgetoptgetopts

how to pass other arguments besides flags


I am trying to execute my file by passing in an absolute path as the first argument ($1). I also want to add flags from that absolute path onward, but i do not know how to tell optargs to start counting from $2 forward since if i pass in the absolute path as the $1 it seems to break the getopts loop.

I'm gussing i have to implement a shift for the first argument in the following code:

while getopts :lq flag; do
case $flag in
l) echo "executing -l flag"
;;
q) echo "executing -q flag"
;;
esac
done

I'm not sure how to approach this. Any tips are welcome, thank you.


Solution

  • getopts does, indeed, stop processing the arguments when it sees the first non-option argument. For what you want, you can explicitly shift the first argument if it is not an option. Something like

    if [[ $1 != -* ]]; then
        path=$1
        shift
    fi
    
    while getopts :lq flag; do
        ...
    done