【问题标题】:How to take 2 argument from getopts如何从 getopts 中获取 2 个参数
【发布时间】:2019-09-04 18:49:09
【问题描述】:

我正在创建一个 bash 脚本,它将来自命令行的用户的两个参数。但我不确定如何从用户那里获取 2 个参数,如果没有传递这两个参数,则会显示错误并从脚本返回。下面是我用来从用户那里获取参数的代码,但目前我的 getopts 只接受一个参数。

optspec="h-:"
while getopts "$optspec" optchar; do
  case "${optchar}" in
    -)
      case "$OPTARG" in
        file)
          display_usage ;;
        file=*)
          INPUTFILE=${OPTARG#*=};;
      esac;;
    h|*) display_usage;;
  esac
done

如何添加一个选项以从命令行获取更多参数。如下所示

script.sh --file="abc" --date="dd/mm/yyyy"

【问题讨论】:

  • @chepner 我想做这样的事情 script.sh --file="abc" --date="dd/mm/yyyy"
  • getopts 也不做长选项。
  • 如果两个参数都需要,不要将它们设为选项(以-开头),将它们设为位置参数。
  • @chepner 你能建议我们如何从 getopt 做到这一点
  • 为什么要使用这种语法?您可以编写零代码并将脚本调用为file=abc date=dd/mm/yy script.sh。如果要解析参数,请以script.sh file=abc date=dd/mm/yy 调用脚本。额外的-- 没有额外的价值。

标签: bash shell getopts


【解决方案1】:

getopts 不支持长参数。它只支持单字母参数。

您可以使用getopt。它不像getopts 那样广泛可用,它来自posix,随处可用。 getopt 肯定会在任何 Linux 上可用,而不仅仅是。在 linux 上,它是 linux-utils 的一部分,这是一组最基本的实用程序,例如 mountswapon

典型的getopt 用法如下:

if ! args=$(getopt -n "your_script_name" -oh -l file:,date: -- "$@"); then
    echo "Error parsing arguments" >&2
    exit 1
fi
# getopt parses `"$@"` arguments and generates a nice looking string
# getopt .... -- arg1 --file=file arg2 --date=date arg3
# would output:
# --file file --date date -- arg1 arg2 arg3
# the idea is to re-read bash arguments using `eval set`
eval set -- "$args"
while (($#)); do
   case "$1" in
   -h) echo "help"; exit; ;;
   --file) file="$2"; shift; ;;
   --date) date="$2"; shift; ;;
   --) shift; break; ;;
   *) echo "Internal error - programmer made an error with this while or case" >&2; exit 1; ;;
   esac
   shift
done

echo file="$file" date="$date"
echo Rest of arguments: "$@"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2011-10-06
    • 2020-07-28
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多