cbdeveloper
cbdeveloper

Reputation: 31365

Check if parameter does NOT match regex with two possible values?

Here is what I'm trying to do in one of my bash scripts.

If SERVER_ENV is not PROD or TEST, the script must exit.

check-server-env() {
  local SERVER_ENV="$1"
  if ! [[ "$SERVER_ENV"^^ =~ ^(TEST|PROD)$ ]]; then
    error "$(highlight "$SERVER_ENV")" " does not exist."
    echo "Exiting script..."
    echo ""
    exit 0
  fi
}

I call script.sh TEST

SERVER_ENV=$1

check-server-env $SERVER_ENV

Here is how I'm calling. And it's not working. What am I doing wrong?

Upvotes: 3

Views: 2563

Answers (2)

anubhava
anubhava

Reputation: 785156

You may use:

check-server-env() {
  local SERVER_ENV="$1"

  if [[ ! "${SERVER_ENV^^}" =~ ^(TEST|PROD)$ ]]; then
    error "$(highlight "$SERVER_ENV")" " does not exist."
    echo "Exiting script..."
    echo ""
    exit 0
  fi
}

However you may ditch regex and use extglob matching in bash:

check-server-env() {
  local SERVER_ENV="$1"

  if [[ "${SERVER_ENV^^}" != @(TEST|PROD) ]]; then
    error "$(highlight "$SERVER_ENV")" " does not exist."
    echo "Exiting script..."
    echo ""
    exit 0
  fi
}

Upvotes: 6

MonkeyZeus
MonkeyZeus

Reputation: 20737

Why use regex at all?

if [ "${SERVER_ENV^^}" != "PROD" ] && [ "${SERVER_ENV^^}" != "TEST" ]; then
    error "$(highlight "$SERVER_ENV")" " does not exist."
    echo "Exiting script..."
    echo ""
    exit 0
fi

Upvotes: 1

Related Questions