I have the following piece of a script:

set ${DB_TYPE:='mysqli'}

echo $DB_TYPE

if [  $DB_TYPE -eq "mysqli"  -o  $DB_TYPE -eq "mariadb"  ]; then
      #Do some stuff
else
  echo >&2 "This database type is not supported"
   echo >&2 "Did you forget to -e DB_TYPE='mysqli' ^OR^ -e DB_TYPE='mariadb' ?"
  exit 1
fi

But this piece of script somehow fails on:

if [  $DB_TYPE -eq "mysqli"  -o  $DB_TYPE -eq "mariadb"  ]; then

So how can I compare if $DB_TYPE id either "mysqli" or "mariadb"?

share|improve this question
up vote 2 down vote accepted

It would be useful to know how it fails but there are a few things obviously wrong with the following:

if [  $DB_TYPE -eq "mysqli"  -o  $DB_TYPE -eq "mariadb"  ]; then
  • variables are unquoted (dangerous within [)
  • -eq is for comparing integers, = should be used for strings (see this question for detailed discussion of the difference)

As you've tagged then you should be aware of the improved [[ which allows you to write this:

if [[ $DB_TYPE = mysqli || $DB_TYPE = mariadb ]]; then

Within [[ you don't need to quote your variables and you can use || as a logical or.

You might also consider using this:

case $DB_TYPE in
    mysqli|mariadb)
        # do one thing
        ;;
    *)
        # do other stuff
        ;;
esac
share|improve this answer

-eq means equals to. It is for integer numbers, not strings. For strings use =, like:

if [ "$DB_TYPE" = "mysqli" ] || [ "$DB_TYPE" = "mariadb" ]; then
share|improve this answer

If you have a recent version of bash, you can use the extended regular expression matching built in via the equal tilde (=~) operator.

#!/bin/bash

if [[ "$DB_TYPE" =~ ^(mysqli|mariadb)$ ]]; then
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.