Search code examples
bashparametersargumentsgetopt

Getopts doesn't work when there is a bash parameter before


I have a problem with using getopts and simple bash parameters. My script write out from the file lines that match the specified expression.

-f option allows you to change file

-n option to change the number of lines written out

The first parametr $1 determines the type of expression

Example file (file.txt):

aaaaaaaaaaaa
bbbbbbbbbbba
cccccccccccc
ab
ac
dddddddddddd
dgdgdgdgdgdg
abdbdbdbdbdb

Example order:

./script.sh a -f file.txt -n 2

Example output:

aaaaaaaaaaaa
ab

My script:

while getopts ":n:f:" opt
        do
        case $opt in
        (n)  
                argn=$OPTARG
                ;;
        (f)
                argf=$OPTARG
                ;;
        esac
        done

FOO=${argf:=/etc/passwd}
NR=${argn:=3}


echo " --------- ^$1 -----------"
awk -F':' '/^'"$1"'/ { print $1 }' $FOO | head -n $NR

It works only for example when I type

 ./script.sh a 

or

./script.sh b 

(giving me lines starting with this letter). Or when I just typed

 ./script.sh -n 5 

or

./script -f file.txt

It doesn't work when I want to use both parametr ($1) and the options. What can I do?

Thanks for your answers!


Solution

  • That's how getopts works. It stops at the first non-option argument.

    If you want to do what you are asking about (and I wouldn't recommend it by the way) then you get to either manually strip your option first (and call getopts normally) or pass the rest of the arguments to getopts manually.

    So either

    opt1=$1
    shift
    
    while getopts ":n:f:" opt
    ....
    done
    
    echo " --------- ^opt1 -----------"
    

    or

    while getopts ":n:f:" opt "${@:2}"
    ....
    done
    
    echo " --------- ^$1 -----------"