AlwaysALearner
AlwaysALearner

Reputation: 6690

Shell script if condition

I'm writing a script which runs the following command

mysql -u root -e "show databases"

and this will display a list of databases.

If this table doesn't contain a database by name "userdb", it should do the following-

if [ ... ]; then
 echo "error"
 exit
fi

What do i write in the if [ ... ] condition?

Upvotes: 0

Views: 825

Answers (2)

Matteo
Matteo

Reputation: 14930

You can check with grep if the table name is listed. grep -q will not print anything to the console but will set the exit status according to the result (the exit status will then be checked by if).

if ! mysql -u root -e 'show databases' | grep -q '^userdb$' ; then
    echo error
    exit
fi

About the regular expression: '^' matches the beginning of the line and '$' matches the end of the line (to avoid a false positive for database names containing userdb, e.g. userdb2)

Upvotes: 2

Laser
Laser

Reputation: 6960

Try this one:

usedb=DBname    
check=`mysql -u root -e "show databases" | grep $userdb`
if [ "$check" != "$userdb" ]; then
 echo "error"
exit
fi

But here will be an error if line with database name contain any other information. Try to workaround it with regexp

Upvotes: 0

Related Questions