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?

anubhava
  • 761,203
  • 64
  • 569
  • 643
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

2 Answers2

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
}
Shane Bishop
  • 3,905
  • 4
  • 17
  • 47
anubhava
  • 761,203
  • 64
  • 569
  • 643
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
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
  • This condition won't match the OP's desired logic. – Shane Bishop Feb 16 '21 at 15:46
  • @ShaneBishop thanks for catching that, fixed! – MonkeyZeus Feb 16 '21 at 15:47
  • 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)"). – Shane Bishop Feb 16 '21 at 15:50