以前有bash参数时,Getopts不起作用

时间:2015-02-03 13:51:47

标签: bash parameters arguments getopt

我在使用getopts和简单的bash参数时遇到问题。我的脚本从与指定表达式匹配的文件行中写出。

-f选项允许您更改文件

-n选项可以更改写出的行数

第一个参数$ 1决定了表达式的类型

示例文件(file.txt):

aaaaaaaaaaaa
bbbbbbbbbbba
cccccccccccc
ab
ac
dddddddddddd
dgdgdgdgdgdg
abdbdbdbdbdb

示例顺序:

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

示例输出:

aaaaaaaaaaaa
ab

我的剧本:

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

仅适用于我输入

的情况
 ./script.sh a 

./script.sh b 

(给我以这封信开头的行)。或者当我输入

 ./script.sh -n 5 

./script -f file.txt

当我想同时使用parametr($ 1)和选项时,它不起作用。我该怎么办?

感谢您的回答!

2 个答案:

答案 0 :(得分:3)

getopts的工作原理。它在第一个非选项参数处停止。

如果你想做你要问的事情(顺便说一下我也不推荐)那么你可以先手动剥离你的选项(并正常呼叫getopts)或通过其余的getopts参数手动。

所以要么

opt1=$1
shift

while getopts ":n:f:" opt
....
done

echo " --------- ^opt1 -----------"

while getopts ":n:f:" opt "${@:2}"
....
done

echo " --------- ^$1 -----------"

答案 1 :(得分:2)

我同意Etan。这是应该做的事情:

# I like to declare my vars up front
# your use of FOO=${argf:=/etc/passwd} is of course OK

file=/etc/passwd
max_matches=3

while getopts ":n:f:" opt; do
    case $opt in
        n) max_matches=$OPTARG ;;
        f) file=$OPTARG ;;
        :) echo "missing argument for option -$OPTARG"; exit 1 ;;
       \?) echo "unknown option -$OPTARG"; exit 1 ;;
    esac
done
shift $((OPTIND-1))    # remove the processed options 
pattern=$1             # NOW, get the search term.

grep -m "$max_matches" "^$pattern" "$file"

然后你将用:

执行它
./script.sh -f file.txt -n 2 a
./script.sh -f file.txt a
./script.sh -n 2 a
./script.sh a

注意,don't use ALL_CAPS_VARS