3

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?

9
  • 1
    The regex is not necessary. You can just do if [ "$SERVER_ENV" != TEST ] && [ "$SERVER_ENV" != PROD ]; then .... Commented Feb 16, 2021 at 15:42
  • 2
    @ShaneBishop I guess it would also work. But I'd like to do it using regex. Thanks! Commented Feb 16, 2021 at 15:45
  • 2
    As pointed out by @anubhava, that's the wrong way to make a string uppercase in bash. The correct way is "${SERVER_ENV^^}" (note the { and }). Commented Feb 16, 2021 at 15:45
  • 1
    Wrong answer linked in dupe, voting to reopen. Commented Feb 16, 2021 at 15:48
  • 3
    Also I don't understand regex tag removal rationale. If OP wants a regex help what's wrong with having it in question? Commented Feb 16, 2021 at 15:52

2 Answers 2

6

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

This condition won't match the OP's desired logic.
@ShaneBishop thanks for catching that, fixed!
Still not fixed - you need &&. Quoting the OP: "If SERVER_ENV is not PROD or TEST, the script must exit." Here the English language is being ambiguous, but the English "not ... or" in this case translates to && in bash, because of De Morgan's law. (The English sentence translates to "not (x or y)", which De Morgan's law translates to "(not x) and (not y)").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.