我可以为参数设置范围吗?

我可以为参数设置范围吗?

我有这个代码:

if [[ $1 = "-s" ]] && [[ $2 = 0-9 ]]
then
  echo "yes"
fi

0-9 对我不起作用。我真正想要的是输入,例如 -x 3 (或任何数字)。

答案1

if [[ $1 = "-s" ]] && [[ $2 -ge 0 ]] && [[ $2 -le 9 ]]

-ge: 大于或等于

-le: 小于或等于

答案2

这是可能的,但你需要使用字符类([0-9])。例如:

if [[ "$1" = "-s" ]] && [[ "$2" = [0-9] ]]
then
    echo "yes"
fi

然而,上述仅适用于$2由单个数字组成的情况。如果您想$2包含一位或多位数字,请使用:

if [[ "$1" = "-s" ]] && [[ "$2" != *[!0-9]* && "$2" = [1-9]* ]]
then
    echo "yes"
fi

在较新的 bash 版本中,您还可以使用正则表达式:

if [[ "$1" = "-s" ]] && [[ "$2" =~ ^[0-9]+$ ]]
then
    echo "yes"
fi

匹配^字符串的开头和$结尾。意思+是“0个或多个”。因此,^[0-9]*$仅当字符串从开头到结尾只包含一个或多个数字时才成立。

答案3

[ "${#1}${1#-s}" = "$((${2%%*[!0-9]*}0?2:-1))" ] &&
echo yes

...如果你平衡比较,有时可以缩短测试。

但我更喜欢case

case ${1#-s}:$2 in
(*:*[!0-9]*|*:) ;;
("${1:+:$2}")   echo yes.
esac

基本上这个想法是排除任何匹配非数字。例如:

[ "${2:+1$2}" = "1${2##*[!0-9]*}" ] && 
echo '"$2"' contains at least one character which \
         is a digit and zero which are not digits.

这要简单得多,case因为您有多个分支。

case $1:$2 in
(*:*?"$2")
    echo '"$1"' contains a "':'";;
(*:*[!0-9]*|*:0*[89]*|*:)
    echo '"$2"' either contains a not-digit character, no characters, \
           or is an invalid octal constant - or perhaps a mix-and-match;;
([!-]*|?[!s]*|??[!:]*)
    echo '"$1"' is either empty, doesn\'t match '-s' in its first two characters, \
          or is more than two characters. Or perhaps a mix-and-match.;;
(*) echo there are no more possibilities other than the one you want.
    echo but you can get here a lot sooner, as demonstrated above.
esac

相关内容