Linux 检查参数是值X还是值Y
我想检查bash脚本中的变量是否等于值1或值2 我不想使用这样的东西,因为当变量等于1或2时,“if true语句”是相同的(一些大的回显文本)。我想避免数据冗余Linux 检查参数是值X还是值Y,linux,bash,if-statement,parameters,equality,Linux,Bash,If Statement,Parameters,Equality,我想检查bash脚本中的变量是否等于值1或值2 我不想使用这样的东西,因为当变量等于1或2时,“if true语句”是相同的(一些大的回显文本)。我想避免数据冗余 if [ $1 == 1 ] ; then echo number 1 ; else if [ $1 == 2 ] ; then echo number 2 ; fi 更像 if [ $1 == 1 OR 2 ] ; then echo number 1 or 2 ; fi 由于要比较整数值,请使用bash算术运算符(()),如下
if [ $1 == 1 ] ; then echo number 1 ; else
if [ $1 == 2 ] ; then echo number 2 ; fi
更像
if [ $1 == 1 OR 2 ] ; then echo number 1 or 2 ; fi
由于要比较整数值,请使用
bash
算术运算符(())
,如下所示:
(( $1 == 1 || $1 == 2 )) && echo "number 1 or 2"
用于使用bash
test="dude"
if [[ "$test" =~ ^(dude|coolDude)$ ]]; then echo "Dude Anyway"; fi
# literally means match test against either of words separated by | as a whole
# and not allow for sub-string matches.
由于要比较整数值,请使用
bash
算术运算符(())
,如下所示:
(( $1 == 1 || $1 == 2 )) && echo "number 1 or 2"
用于使用bash
test="dude"
if [[ "$test" =~ ^(dude|coolDude)$ ]]; then echo "Dude Anyway"; fi
# literally means match test against either of words separated by | as a whole
# and not allow for sub-string matches.
最容易扩展的选项可能是
case
语句:
case $1 in
[12])
echo "number $1"
esac
模式[12]
与1
或2
匹配。对于较大的范围,您可以使用[1-5]
,或更复杂的模式,如[1-9]|[1-9][0-9]
来匹配1
到99
之间的任何数字
当您有多个案例时,应使用
;;分隔每个案例
最容易扩展的选项可能是case
语句:
case $1 in
[12])
echo "number $1"
esac
模式[12]
与1
或2
匹配。对于较大的范围,您可以使用[1-5]
,或更复杂的模式,如[1-9]|[1-9][0-9]
来匹配1
到99
之间的任何数字
当您有多个案例时,应使用
;;分隔每个案例
旁白:=
在[
中不是有效的比较运算符。Bash允许它作为扩展,但只指定字符串比较的=
。可以说是的复制或旁白:=
在中不是有效的比较运算符[
.Bash允许将其作为扩展,但仅指定字符串比较的=
。在当前版本的POSIX标准中,可论证的重复或-o
被明确标记为过时。使用[one]|[one].和=
是一个不可移植的扩展;在[]
中使用=
进行字符串比较(请参阅中的[OB]
标记)-o
在当前版本的POSIX标准中被明确标记为过时。请使用[one]|[one]另一个]
。和=
是不可移植的扩展名;在[]
中使用=
进行字符串比较(请参阅中的[OB]
标记)