【问题标题】:Getopts doesn't work when there is a bash parameter before之前有 bash 参数时 Getopts 不起作用
【发布时间】:2015-04-02 17:57:02
【问题描述】:

我在使用 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

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

感谢您的回答!

【问题讨论】:

  • @JoachimPileborg optstring 中的前导冒号表示“静默模式”。
  • kk,我修好了,但这不是问题的本质,因为在($1)之前有参数时,脚本仍然“看不到”选项。

标签: bash parameters arguments getopt


【解决方案1】:

getopts 就是这样工作的。它在第一个非选项参数处停止。

如果您想做您所要求的事情(顺便说一下,我不建议这样做),那么您可以先手动删除您的选项(并通常调用 getopts)或传递其余参数手动到getopts

所以

opt1=$1
shift

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

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

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

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

【讨论】:

    【解决方案2】:

    我同意伊坦的观点。这是你应该做的:

    # 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

    【讨论】:

    • 谢谢!非常有用的答案。
    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2014-03-09
    • 1970-01-01
    相关资源
    最近更新 更多