2

The following is working as expected.

for schema in `mysql -e"show databases"`
do
if [[ $schema = 'test' ]];then
echo $schema
fi
done

But when I need to select all values starting with test, the following does not work for obvious reasons...

if [[ $schema = 'test%' ]];then

I want to select the other values like test_db, test123 etc.

shantanuo
  • 27,732
  • 66
  • 204
  • 340

4 Answers4

7

You could use bash regexes:

if [[ $schema =~ ^test ]]; then
beny23
  • 32,077
  • 3
  • 78
  • 83
3

Plain shell patterns will work too, since this does not really require a regular expression:

if [[ $schema == test* ]]; ...

See the documentation for [[ ]] -- http://www.gnu.org/software/bash/manual/bashref.html#index-g_t_005b_005b-57

glenn jackman
  • 207,528
  • 33
  • 187
  • 305
2

You can use wildcards (regular expressions) in bash:

pax> if [[ test123 =~ ^test.* ]] ; then echo yes ;fi
yes

From the bash manpage:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)).

The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2.

If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force it to be matched as a string.

Substrings matched by parenthesized sub‐expressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

Community
  • 1
  • 1
paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841
1

Another option is to move the check and do:

for schema in $( mysql -e"show databases" | grep ^test )
William Pursell
  • 174,418
  • 44
  • 247
  • 279