【问题标题】:How do i use getopts to avoid running a script when there is no parameter entered?没有输入参数时,如何使用 getopts 避免运行脚本?
【发布时间】:2016-07-11 14:51:01
【问题描述】:

这是我正在尝试做的事情

while getopts "h?rd" opt; do
    case "$opt" in
    h|\?)
        echo "invalid"
        exit 0
        ;;
    r)  report=1
        ;;
    d)  delete=1
        ;;
    esac
done

-r & -d 工作,作为参数传递的任何其他字符也会发出错误。 但如果我不使用参数,代码也会运行。我也想提示一个错误。我怎样才能做到这一点?

【问题讨论】:

  • 如果我理解正确,[ this ] & [ this ] 应该可以解决您的问题。
  • 我想知道在 case 部分中无效参数的值应该是什么。

标签: linux bash shell unix scripting


【解决方案1】:

您可以使用 bash 的 $# 变量来查找无参数。在getopts中使用case *)也可以获得其他无效参数

#!/bin/bash

if [ $# -lt 1 ]; then
  echo "no arguments"
  exit 1
fi
while getopts ":h\?rd" opt; do
    case "$opt" in
    h|"\?")
        echo "valid"
        exit 0
        ;;
    r)  report=1
        ;;
    d)  delete=1
        ;;
    *)  echo "not valid"
        ;;
    esac
done

【讨论】:

  • 其实可以使用\?)来检测无效选项(如果getopts不能识别选项,则返回?)。
  • ++,但是为了培养良好的习惯,我建议输出错误信息到stderr
【解决方案2】:

但如果我不使用参数,代码也会运行。

getopts 无法帮助您解决这个问题。你可以放

if [ -z "$@" ]
then
echo "No arguments entered.. >&2
echo "Usage command -[h|?|r|]" >&2
exit 1 
fi

在开始处理这种情况。

我还建议对脚本进行一些小的更改,如下所示:

#!/bin/bash

while getopts ":hr:d" opt; do
#adding a colon in the beginning of the optstring supresses the
#system generated error message for invalid options.
    case "$opt" in
    h)
        echo "Help Stuff"
        ;;
    r)  report=1
        echo $report
        ;;
    d)  delete=1
        echo $delete
        ;;
    \?) echo "Invalid option $OPTARG"
        echo "Aborting.."
        exit 1 >&2 # Once an invalid option found abort
    esac
done
shift # Checking for non-option arguments.
[[ $1 = "--" ]] && shift #Non option arguments begin with a --, So you need to 'shift' once more
lastparams=("$@")
echo "${lastparams[@]}"

注意

标准文件描述符是 0(stdin)、1(stdout) 和 2(stderr)。 您可以将&2 替换为/dev/stderr

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2017-12-31
    • 2021-02-26
    • 2020-12-12
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2010-09-24
    相关资源
    最近更新 更多