使用 bash 检查输入的值是否在列表中

使用 bash 检查输入的值是否在列表中

我对 bash 脚本不熟悉。在 bash 脚本中,我尝试根据定义的列表验证提示值,以便当我调用时:

./test.bash [caseyear] [sector]

caseyear 和扇区将在以下尝试的 bash 脚本中进行验证:

Validating Year
#1 Check the value of the caseyear Parameter
if [ "$1" -eq "$1" 2> /dev/null ]; then
  if [ $1 -ge 2009 ]; then
    export caseyear=$1
  else
    echo -e "\n\tSpecify [caseyear] value greater than or equal to 2009.\n"
    exit 4
  fi
else
  echo -e "\n\tSpecify [caseyear] value greater than or equal to 2009.\n"
  exit 3
fi

我无法验证输入的值必须位于扇区列表中,因此我尝试了以下脚本:

Validating Sector

#sector list
list_of_sectors="11 40 44_45 52 10_11"

#1 Check if sector value is in the sector list
$ function exists_in_list() {
    LIST=$1
    DELIMITER=$2
    VALUE=$3
    LIST_WHITESPACES=`echo $LIST | tr "$DELIMITER" " "`
    for x in $LIST_WHITESPACES; do
        if [ "$x" = "$VALUE" ]; then
            return 0
        fi
    done
    return 1
}

#2 Check if sector is null
if [ -z "$2" ]; then
    echo -e "\n\tSpecify [caseyear] sector value.\n"
    exit 2
else
  #export omitflag="$(echo $2 | tr '[a-z]' '[A-Z]')" #Convert to upper case
#3 Check if sector value is in the sector list
  export sector

#------------------->Problem Area
#How do I pass the entered $sector value to exists_in_list function that matches with the list, $list_of_sectors?

  if [ $(exists_in_list $list_of_sectors) -ne 0 ] ; then
    echo -e "\n\tSpecify [sector] sector value.\n"
    exit 1
  fi
fi

echo -e "\nYou Specified - CaseYear:$caseyear, Sector:$sector"

谢谢你!

答案1

使用语句最容易做到这一点case ... esac

#!/bin/sh

caseyear=$1
sector=$2

if [ "$#" -ne 2 ]; then
    echo 'expecting two arguments' >&2
    exit 1
fi

if [ "$caseyear" -lt 2009 ]; then
    echo 'caseyear (1st arg) should be 2009 or larger' >&2
    exit 1
fi

case $sector in
    11|40|44_45|52|10_11)
        # do nothing
        ;;
    *)
        # error
        echo 'sector (2nd arg) is not in list' >&2
        exit 1
esac

printf 'Got caseyear="%s" and sector="%s"\n' "$caseyear" "$sector"

该脚本不使用任何bash特定于 的内容,因此我将解释器更改为/bin/sh.

如果脚本没有精确地获得两个参数,它将立即退出。它通过确保第一个参数在数值上大于或等于 2009 来验证它。它通过将第二个参数与语句|中 - 分隔列表中的条目进行匹配来验证第二个参数case

case语句也可以用更少的行数编写,如下所示

case $sector in
        (11|40|44_45|52|10_11) ;;
        (*) echo 'sector (2nd arg) is not in list' >&2; exit 1 ;;
esac

每种情况下模式字符串的左括号都是可选的。最后一个案例之后的内容;;也是可选的。

$1和两个变量的初始赋值$2可以更花哨一些,这引入了额外的检查以确保两个参数都存在并且它们不是空字符串:

caseyear=${1:?'1st argument caseyear must be specifiend and not empty'}
sector=${2:?'2nd argument sector must be specified and not empty'}

如果变量未设置或为空,扩展将导致输出${variable:?string}字符串。如果发生这种情况,脚本将以非零退出状态终止。这将使我们能够放弃对 的测试。stringvariable$#

据我所知,不需要导出这两个变量。如果您正在启动一些在其环境中需要这些变量的外部工具,您可以在运行外部工具之前在上面的代码末尾一次性导出它们,使用

export caseyear sector
some-other-utility

相关内容