为什么第3个参数没有在getopts bash中解析

时间:2014-12-09 07:30:08

标签: bash shell getopts

我正在尝试编写一个简单的脚本来根据输入参数执行某些操作。这是我写的

#!/bin/bash
usage() { echo "Usage: $0 [-l <string>] [-p <string>] [-d <string> ]" 1>&2; exit 1; }

while getopts ":l:p:d" o; do
    case "${o}" in
        l)
            l=${OPTARG}
        echo "$l"
            ;;
        p)
            p=${OPTARG}
        echo "$p"
            ;;
        d)
            d=${OPTARG}
        echo "$d"
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${l}" ] && [ -z "${p}" ] && [ -z "${d}" ]; then
    usage
fi

它能够正确解析以-l-p给出的输入,但不会解析第三个输入-d

输出:

sagar@CPU:~/$ ./play.sh -l "l is parsed" -p "p is parsed" -d "d is parsed"
l is parsed
p is parsed

这有效

sagar@CPU:~/$ ./play.sh -p "p is parsed"
p is parsed

虽然这不起作用

sagar@CPU:~/$ ./play.sh -d "d is parsed"

Usage: ./play.sh [-l <song name>] [-p <song name>] [-d <song name> ]

我在这里做错了什么? 感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您在while语句传递参数

时缺少:
#!/bin/bash
usage() { echo "Usage: $0 [-l <string>] [-p <string>] [-d <string> ]" 1>&2; exit 1; }

while getopts ":l:p:d:" o; do
    case "${o}" in
        l)
            l=${OPTARG}
        echo "$l"
            ;;
        p)
            p=${OPTARG}
        echo "$p"
            ;;
        d)
            d=${OPTARG}
        echo "$d"
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${l}" ] && [ -z "${p}" ] && [ -z "${d}" ]; then
    usage
fi

运行:

./script.sh -l "l is parsed" -p "p is parsed" -d "d is parsed"

输出

l is parsed
p is parsed
d is parsed

运行:

./script.sh -d "d is parsed"

输出

d is parsed