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!