检查参数是值 X 还是值 Y
Check if parameter is value X or value Y
我想在我的 bash 脚本中检查变量是否等于值 1 或等于值 2。
我不想使用这样的东西,因为 'if true statements' 是相同的(一些大回显文本),当变量等于 1 或 2 时。我想避免数据冗余。
if [ == 1 ] ; then echo number 1 ; else
if [ == 2 ] ; then echo number 2 ; fi
更多类似
if [ == 1 OR 2 ] ; then echo number 1 or 2 ; fi
由于您要比较整数值,请使用 bash
算术运算符 (())
,如
(( == 1 || == 2 )) && echo "number 1 or 2"
对于 handling-strings 在 bash
中使用 regex
运算符
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 in
[12])
echo "number "
esac
模式 [12]
匹配 1
或 2
。对于更大的范围,您可以使用 [1-5]
或更复杂的模式,如 [1-9]|[1-9][0-9]
来匹配从 1
到 99
.
的任何数字
当您有多个案例时,您应该用 ;;
.
分隔每个案例
我想在我的 bash 脚本中检查变量是否等于值 1 或等于值 2。
我不想使用这样的东西,因为 'if true statements' 是相同的(一些大回显文本),当变量等于 1 或 2 时。我想避免数据冗余。
if [ == 1 ] ; then echo number 1 ; else
if [ == 2 ] ; then echo number 2 ; fi
更多类似
if [ == 1 OR 2 ] ; then echo number 1 or 2 ; fi
由于您要比较整数值,请使用 bash
算术运算符 (())
,如
(( == 1 || == 2 )) && echo "number 1 or 2"
对于 handling-strings 在 bash
regex
运算符
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 in
[12])
echo "number "
esac
模式 [12]
匹配 1
或 2
。对于更大的范围,您可以使用 [1-5]
或更复杂的模式,如 [1-9]|[1-9][0-9]
来匹配从 1
到 99
.
当您有多个案例时,您应该用 ;;
.