Bash脚本中验证输入参数是否在指定列表的问题求助
Bash脚本Sector参数验证问题解决
原代码存在的问题
- sector变量未赋值:仅
export sector但未将用户输入的第二个参数$2赋值给它,导致后续检查时$sector为空。 - 函数调用参数缺失:
exists_in_list函数需要三个参数(目标列表、分隔符、待检查值),原调用仅传入了列表,缺少分隔符和待验证的sector值。 - 返回值判断方式错误:原代码用
$(exists_in_list ...)捕获函数输出,但该函数通过返回状态码(0表示存在,1表示不存在)而非输出来传递结果,应直接通过函数的退出状态判断。
修正后的完整代码
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() { local LIST="$1" local DELIMITER="$2" local VALUE="$3" # 将列表按分隔符替换为空格,方便遍历 local 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 a sector value.\n" exit 2 else # 将输入的第二个参数赋值给sector并导出 export sector="$2" #3 Check if sector value is in the sector list # 完整传入函数所需的三个参数 if ! exists_in_list "$list_of_sectors" " " "$sector"; then echo -e "\n\tInvalid sector value. Allowed values are: $list_of_sectors\n" exit 1 fi fi echo -e "\nYou Specified - CaseYear:$caseyear, Sector:$sector"
关键修正说明
- 变量赋值:将用户输入的第二个参数
$2赋值给sector,确保待验证的是实际输入值。 - 函数调用:完整传入三个参数:目标列表
$list_of_sectors、分隔符" "(原列表用空格分隔)、待检查值$sector。 - 状态判断:用
if ! exists_in_list ...; then逻辑,当函数返回1(未找到匹配)时触发错误提示。 - 代码健壮性:函数内用
local声明变量避免污染全局环境,所有变量引用加双引号,防止空格或特殊字符导致的解析错误。 - 提示优化:错误提示明确告知用户允许的sector取值范围,提升易用性。
内容的提问来源于stack exchange,提问作者lydias
相关产品推荐
相关产品推荐

