如何改变 [[ ! $number =~ ^[0-9]+$ ]] 到 BASH 中的单词选项?

如何改变 [[ ! $number =~ ^[0-9]+$ ]] 到 BASH 中的单词选项?

我的脚本中有一个输入,用于写入运行某些软件所需的文件,但是该软件仅允许 2 个可能的选项之一,即 LO 和 LDO。

我已经编写的输入位于以下代码的顶部,底部的代码是建议我要操作的代码

我想要一个问题“重叠(LO 或 LDO):”,如果未输入其中一个选项,则会出现一条错误消息,并重复该步骤,而不是再次遍历整个脚本,而不是搜索 0 和 0 之间的值9

据我所知,我需要更改 ^[0-9] 以包括 LO 和 LDO,但我不确定标点符号是什么或如何做

### My Script ###
read -p "Overlap (LO or LDO): " OVERLAP

### Recommended Script ###
#!bin/bash
number=""
while [[ ! $number =~ ^[0-9]+$ ]]; do
    echo Please enter your age
    read number
done
echo You are $number years old

答案1

输入和验证循环通常写成这样:

while true; do
    read -p 'Overlap (LO or LDO): ' overlap

    case $overlap in
        LO|LDO) # ok
            break
            ;;
        *) # not ok
            echo 'Please enter LO or LDO' >&2
    esac
done

即,当您验证答案正确时,您会打破无限循环。

显然,你也可以这样做

while true; do
    read -p 'Overlap (LO or LDO): ' overlap

    if [ "$overlap" = LO ] || [ "$overlap" = LDO ]; then
        # ok
        break
    fi
    # not ok
    echo 'Please enter LO or LDO' >&2
done

或者,使用具有以下功能的外壳select

echo 'Select overlap:' >&2
select overlap in LO LDO; do
    case $REPLY in
        [12]) # ok
            break
            ;;
        *) # not ok
            echo 'Please select LO or LDO' >&2
    esac
done

答案2

您可以使用&&and 运算符:

#! /bin/bash
overlap=""
first=1
while [[ $overlap != LO && $overlap != LDO ]] ; do
    if [[ ! $first ]] ; then
        echo 'Wrong answer, please answer LO or LDO!' >&2
    fi
    read -p 'Overlap (LO or LDO): ' overlap
    unset first
done

您还可以使用正则表达式:

until [[ $overlap =~ ^LD?O$ ]] ; do
    ...
  • ^匹配字符串的开头
  • ?使前面的事情可选
  • $匹配字符串的结尾

答案3

另一种方法

while read -p "Overlap (LO or LDO): " overlap;
do
 [[ "$overlap" =~ ^LD?O$ ]] && break || echo "Not LO or LDO"
done

相关内容