Bash if中的like子句
以下各项按预期工作Bash if中的like子句,bash,shell,if-statement,Bash,Shell,If Statement,以下各项按预期工作 for schema in `mysql -e"show databases"` do if [[ $schema = 'test' ]];then echo $schema fi done 但是,当我需要从test开始选择所有值时,由于明显的原因,下面的方法不起作用 if [[ $schema = 'test%' ]];then 我想选择其他值,如test_db、test123等。您可以在bash中使用通配符(正则表达式): pax> if [[ test123
for schema in `mysql -e"show databases"`
do
if [[ $schema = 'test' ]];then
echo $schema
fi
done
但是,当我需要从test开始选择所有值时,由于明显的原因,下面的方法不起作用
if [[ $schema = 'test%' ]];then
我想选择其他值,如test_db、test123等。您可以在bash
中使用通配符(正则表达式):
pax> if [[ test123 =~ ^test.* ]] ; then echo yes ;fi
yes
从bash
手册页:
另外还有一个二进制运算符=~,其优先级与==和!=相同。使用时,运算符右侧的字符串被视为扩展正则表达式,并进行相应的匹配(如正则表达式(3))
如果字符串与模式匹配,则返回值为0,否则返回值为1。如果正则表达式语法不正确,则条件表达式的返回值为2
如果启用了shell选项nocasematch,则执行匹配时不考虑字母字符的大小写。可以引用模式的任何部分,以强制将其作为字符串进行匹配
由正则表达式中带括号的子表达式匹配的子字符串保存在数组变量BASH_REMATCH中。索引为0的BASH_REMATCH元素是字符串中与整个正则表达式匹配的部分。索引为n的BASH_REMATCH元素是字符串中与第n个括号中的子表达式匹配的部分
您可以使用bash正则表达式:
if [[ $schema =~ ^test ]]; then
普通shell模式也可以,因为这实际上不需要正则表达式:
if [[ $schema == test* ]]; ...
请参阅
[[]]
--的文档另一个选项是移动支票并执行:
for schema in $( mysql -e"show databases" | grep ^test )
检查数组是否包含bash中的值: