JBerto
JBerto

Reputation: 263

IF statement to change value of a variable

I have the below logic in a script that looks at the value of the variable "LIVE_ALIAS" to see if it has -A in the value. If it does it suppose to change the -A to a -B.

When I run my code the output of LIVE_ALIAS is DEV-A, so my logic "should" change -A to -B, however in the log of my job I see that the else statement is run and thru the value is left as -A and not change. Is there something I'm missing in the 'then' section of the if clause that is causing it not to execute?

Worth noting that is the LIVE_ALIAS is DEV-B, the script runs fine and sets the STAGING_ALIAS to DEV-A

      if [ "${LIVE_ALIAS}" = *"-A"* ]
    then
      STAGING_ALIAS=$(echo "${LIVE_ALIAS}" | sed 's/-A/-B/g')
    else
      STAGING_ALIAS=$(echo "${LIVE_ALIAS}" | sed 's/-B/-A/g')
  fi





> + LIVE_ALIAS=DEV-A
> + [ DEV-A = *-A* ]
> + echo DEV-A
> + sed s/-B/-A/g
> + STAGING_ALIAS=DEV-A


+ LIVE_ALIAS=DEV-B
+ [ DEV-B = *-A* ]
+ echo DEV-B
+ sed s/-B/-A/g
+ STAGING_ALIAS=DEV-A

Upvotes: 0

Views: 1547

Answers (3)

15 Volts
15 Volts

Reputation: 2077

You can match regex here, but you need to wrap the condition within two box brackets. For example:

LIVE_ALIAS="DEV-A"

if [[ "$LIVE_ALIAS" =~ -A ]]
    then
        STAGING_ALIAS=$(echo "$LIVE_ALIAS" | sed 's/-A/-B/g')
    else
        STAGING_ALIAS=$(echo "$LIVE_ALIAS" | sed 's/-B/-A/g')
fi

This should work in SH, BASH and ZSH.

Upvotes: 1

Léa Gris
Léa Gris

Reputation: 19555

If you use Bash built-in RegEx, do it fully:

#!/usr/bin/env bash

LIVE_ALIAS="DEV-A"

if [[ $LIVE_ALIAS =~ (.+-)([AB]) ]]; then
  if [[ ${BASH_REMATCH[2]} == "A" ]]; then
    STAGING_ALIAS="${BASH_REMATCH[1]}B"
  else
    STAGING_ALIAS="${BASH_REMATCH[1]}A"
  fi
fi

(.+-)([AB]): Captures the radical of one ore more of any characters followed by dash into BASH_REMATCH[1], and captures the A or B suffix into BASH_REMATCH[2].

Then depending on suffix, keeps the radical part from BASH_REMATCH[1] and switches the suffix from A→B or B→A.

Upvotes: 1

Quasímodo
Quasímodo

Reputation: 4004

The glob pattern comparison is only available for bash special operator [[:

LIVE_ALIAS="DEV-A"
if [[ "${LIVE_ALIAS}" = *-A* ]]; then
    STAGING_ALIAS=$(echo "${LIVE_ALIAS}" | sed 's/-A/-B/g')
else
    STAGING_ALIAS=$(echo "${LIVE_ALIAS}" | sed 's/-B/-A/g')
fi
echo $STAGING_ALIAS

That outputs DEV-B.

Upvotes: 1

Related Questions