【问题标题】:Bash getopts doesn't show error for second optionBash getopts 不显示第二个选项的错误
【发布时间】:2018-02-19 19:30:37
【问题描述】:

我希望脚本接受两个选项,这两个选项都是必需的。如果我传入一个,脚本不会打印要求您传入第二个的错误。

-bash-4.2$ bash test.sh -b
Invalid option: b requires an argument

-bash-4.2$ bash test.sh -p
Invalid option: p requires an argument

-bash-4.2$ bash test.sh -b sdfsfd

-bash-4.2$ bash test.sh -p sdfsfd

-bash-4.2$ bash test.sh -b sdfsfd -s sfd
Invalid option: s

代码

showHelp()
{
cat << EOF

Find files in client's folder and upload to S3 bucket.

Usage: $(basename $0) [-p PATH_TO_SEARCH] [-b S3 bucket]

OPTIONS:
  -h    Show this help message
  -p    Path to search
  -b    S3 Bucket

EOF
exit 1
}

while getopts ":p:b:h" o; do
    case "${o}" in
        h)
           showHelp
           ;;
        p)
            p=${OPTARG}
            ;;
        b)
            b=${OPTARG}
            ;;
        \? )
            echo "Invalid option: $OPTARG";;
         : )
            echo "Invalid option: ${OPTARG} requires an argument";;
    esac
done
shift $((OPTIND-1))

if [ -z "${p}" ]; then
   showHelp
fi

if [ -z "${b}" ]; then
   showHelp
fi

【问题讨论】:

  • 在每个case语句中添加一个计数器或一个标志,在case语句之后检查它们是否正确。
  • GNU bash, version 4.3.46(2)-release (x86_64-pc-msys) 上工作正常,你有哪个版本的bash
  • GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)
  • 我不知道(根据您发布的内容),变量 bp 是否已设置(在此脚本中或在调用脚本之前);我通常做的是...就在while getops... 之前,我确保我的选项变量未定义,例如:unset b p while getopts ... 以便选项变量的 getopts 后测试按预期工作
  • @markp 它们之前没有设置。

标签: bash getopts


【解决方案1】:

如果您想确保获得 both 选项,您可以使用以下内容:

no_p=1
no_b=1

while getopts ":p:b:h" o; do
    case "${o}" in
        h)
           showHelp
           ;;
        p)
            p=${OPTARG}
            no_p=0
            ;;
        b)
            b=${OPTARG}
            no_b=0
            ;;
        \? )
            echo "Invalid option: $OPTARG";;
         : )
            echo "Invalid option: ${OPTARG} requires an argument";;
    esac
done

[[ $no_p -eq 1 ]] && echo "No -p provided" && exit 1
[[ $no_b -eq 1 ]] && echo "No -b provided" && exit 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 2016-03-10
    • 2015-07-16
    • 2013-04-17
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    相关资源
    最近更新 更多