首页 > 解决方案 > 检查作为 shell 脚本输入提供的可变数量的位置参数的有效性

问题描述

对于为多个平台编译一组应用程序,需要设置某些构建导出。

示例命令如下:

source exports_file.sh <plaforms> <feature1> <feature2> <feature3>

这里位置参数<platform>是必需的,而其他参数如是<feature1>, <feature2>, <feature3>可选的。只有在构建中需要相应的功能时,才必须启用这些功能。

一组有效的命令行选项是:

source exports_file.sh <plaforms> <feature1> <feature2> <feature3> source exports_file.sh <plaforms> <feature1> <feature2> source exports_file.sh <plaforms> <feature1> source exports_file.sh <plaforms>

需要注意的重要一点是,如果出现以下情况,脚本应该返回错误:

1)<platform>输入参数不是由用户提供的。

2)<platform>输入参数的值不在列表中,即它不是 1234、1235 或 1236。

3) 提供除此之外的任何其他特征<feature1>, <feature2>, <feature3>作为输入。

我编写了一个运行良好的脚本,但我不确定它是否正确检查所有输入参数的有效性。

   $> cat exports_file.sh


    if [ $# -gt 0 ]; then

    platform=$1

    # Common exports
    unset PLATFORM
    unset ENABLE_FEATURE_1
    unset ENABLE_FEATURE_2
    unset ENABLE_FEATURE_3

    echo "INFO: Setting common exports for $platform"
    if [ $platform == "1234" ]
    then
        export PLATFORM=91234

    elif [ $platform == "1235" ]
    then
        export PLATFORM=91235

    elif [ $platform == "1236" ]
    then
        export PLATFORM=91236

    else
        echo "ERROR: Exports are not defined for $platform."
        exit 1
    fi

    # Check for feature based exports <feature1> <feature2> <feature3>
    for var in "$@"
    do
        if [ $var == "arg2" ]
        then
            export ENABLE_FEATURE_1=Y

        elif [ $var == "arg3" ]
        then
            export ENABLE_FEATURE_2=Y

        elif [ $var == "arg4" ]
        then
            export ENABLE_FEATURE_3=Y
        else
            echo "ERROR: unrecognised argument '$var'";
            exit 1
        fi
    done
else
    echo "ERROR: No inputs parameters provided to the scripts."
    echo "Usage: source exports_file.sh <plaforms> <feature1> <feature2> <feature3>"
fi`

有没有更好的方法来编写这个脚本。最重要的是保证所有输入参数的有效性。

标签: linuxbashshellsh

解决方案


case语句将简化您的代码。但是,首先,当您发现错误时尽快退出,以便您的其余代码不需要缩进。

if [ $# = 0 ]; then
    echo "ERROR: No inputs parameters provided to the scripts." >&2
    echo "Usage: source exports_file.sh <plaforms> <feature1> <feature2> <feature3>" >&2
    exit 1
fi

platform=$1
shift

echo "INFO: Setting common exports for $platform" >&2
case $platform in 
    1234|1235|1236) export PLATFORM=9$platform ;;
    *) echo "ERROR: Exports are not defined for $platform" >&2
       exit 1 ;;
esac


# Check for feature based exports <feature1> <feature2> <feature3>
for var in "$@"
do
    case $var in
      arg2) export ENABLE_FEATURE_1=Y ;;
      arg3) export ENABLE_FEATURE_2=Y ;;
      arg4) export ENABLE_FEATURE_3=Y ;;
      *) echo "ERROR: unrecognized argument '$var'" >&2
         exit 1;;
    esac
done

推荐阅读