繁体   English   中英

如何使用getopts在bash中采用多个参数?

[英]How can I take multiple arguments in bash using getopts?

我是第一次使用getopts。 我试图接受2个参数: startyearendyear ,脚本将根据这些参数继续进行大量计算。 但是我无法完成这项工作。

我在回声变量方面空白。 我究竟做错了什么?

!/bin/bash

while getopts 'hse:' OPTION; do
  case "$OPTION" in
    h)
      echo "h stands for h"
      ;;

    s)
      startyear="$OPTARG"
      echo "The value provided is $OPTARG"
      ;;

    e)
      endyear="$OPTARG"
      echo "The value provided is $OPTARG"
      ;;
    ?)
      echo "script usage: $(basename $0) [-l] [-h] [-a somevalue]" >&2
      exit 1
      ;;
  esac
done
shift "$(($OPTIND -1))"

echo "The value provided is $startyear and $endyear"

根据Gordon Davisson的建议进行了更新。

您需要在s和e后面都包含“:”,以表示这些选项需要参数。

#!/bin/bash

function help() {
    # print the help to stderr
    echo "$(basename $0) -h -s startyear -e endyear" 2>&1
    exit 1
}

# Stop script if no arguments are present
if (($# == 0))
then
    help
fi

while getopts 'hs:e:' OPTION; do
  case "$OPTION" in
    h)
      help
      ;;
    s)
      startyear="$OPTARG"
      ;;

    e)
      endyear="$OPTARG"
      ;;
  esac
done
shift "$(($OPTIND -1))"

# Checking if the startyear and endyear are 4 digits
if [[ ! ${startyear} =~ ^[0-9]{4,4}$ ]] || [[ ! ${endyear} =~ ^[0-9]{4,4}$ ]]
then
    echo "Error: invalid year" 2>&1
    help
fi

echo "The value provided is $startyear and $endyear"

我的测试运行以上。

$ ./geto -s 2018 -e 2020
The value provided is 2018
The value provided is 2020
The value provided is 2018 and 2020
$

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM