0

我正在尝试使用getopts它来创建一个脚本,它可以作为wc. 问题是当我同时使用两个开关时会卡住。剧本:

while getopts l:w:c: choice
do
         case $choice in
               l) wc -l $OPTARG;;
               w) wc -w $OPTARG;;
               c) wc -c $OPTARG;;
               ?) echo wrong option.
         esac
done

当我用它运行这个脚本时,./script.sh -l file它可以工作,但是当我使用./script -wl file它时,它就会进入一个无限循环。谁能解释发生了什么以及如何解决它?

4

4 回答 4

4

你使用不正确。根据getopts 手册

如果一个字母后跟一个冒号,则该选项应该有一个参数。

在您的示例中,您没有为-w-l选项传递参数;

正确用法是:

./script -w file1 -l file2

这将正确处理这两个选项。

否则,要支持不带参数的选项,只需使用不带冒号的选项,如下所示:

while getopts "hl:w:c:" choice

这里选项h不需要参数,但 l、w、c 将支持一个。

于 2013-07-12T20:55:39.223 回答
3

您需要在 case 语句中构建选项,然后执行wc

# Set WC_OPTS to empty string
WC_OPTS=();
while getopts lwc choice
do
     case $choice in
            l) WC_OPTS+='-l';;
            w) WC_OPTS+='-w';;
            c) WC_OPTS+='-c';;
            ?) echo wrong option.
     esac
done
# Call wc with the options
shift $((OPTIND-1))
wc "${WC_OPTS[@]}" "$@"
于 2013-07-12T20:55:32.410 回答
1

To add to the other comments . . . the version of wc that I have handy seems to handle its options like this:

#!/bin/bash

options=()
files=()

while (( $# > 0 )) ; do
    if [[ "$1" = --help || "$1" = --version ]] ; then
        wc "$1"   # print help-message or version-message
        exit
    elif [[ "${1:0:1}" = - ]] ; then
        while getopts cmlLw opt ; do
            if [[ "$opt" = '?' ]] ; then
                wc "$1"   # print error-message
                exit
            fi
            options+="$opt"
        done
        shift $((OPTIND-1))
        OPTIND=1
    else
        files+="$1"
        shift
    fi
done

wc "${options[@]}" "${files[@]}"

(The above could be refined further, by using a separate variable for each of the five possible options, to highlight the fact that wc doesn't care about the order its options appear in, and doesn't care if a given option appears multiple times.)

于 2013-07-12T21:58:55.723 回答
0
Got a workaround.

#!/bin/bash

if [ $# -lt 2 ]
then

    echo not a proper usage
    exit

fi

file=$2

while getopts wlc choice

do

    case $choice in 

        l) wc -l $file
            ;;
        w) wc -w $file
            ;;
        c) wc -c $file
            ;;
        ?) echo thats not a correct choice

    esac
done

I think I got obsessed with OPTARG, thanks everyone for your kind help 
于 2013-07-13T12:04:52.430 回答