0

I'm trying to pass ip_addr (if env = qa, then pass this ip_addr=x.x.x.47 or else ip_addr=x.x.x.53) using ternary operator and also tried using if condition. When I use ternary operator, I'm getting operand expected (error token is ""qa"? error. And, with if condition, error: url is not calling properly and if condition is failing. Could someone help me to fix this issue ? Also, please suggest any other way to fix this issue. Thanks in Advance !

##2: Using ternary operator

#! /bin/bash
env=qa
username=testuser
pass=password

ip_addr = $(( $env == "qa" ? "x.x.x.47" : "x.x.x.53"))

export id=`curl -u "$username:$pass" \
-H 'Accept: application/vnd.go.cd.v4+json' \
-H 'Content-Type: application/vnd.go.cd.v4+json; charset=utf-8' \
'http://'${ip_addr}':8080/test/api/cases'| grep -i '"id":'`

echo "Expected Id is ${id}"


##2: Using if condition

#! /bin/bash
env=uat
username=testuser
pass=password

if (${env} == "qa"); then
    ip_addr = "x.x.x.47"
else
    ip_addr = "x.x.x.53"
fi

export id=`curl -u "$username:$pass" \
-H 'Accept: application/vnd.go.cd.v4+json' \
-H 'Content-Type: application/vnd.go.cd.v4+json; charset=utf-8' \
'http://'${ip_addr}':8080/test/api/cases' | grep -i '"id":'`

echo "Expected Id is ${id}"
  • Have you tried using https://www.shellcheck.net/ to check your code? It looks like you may have some issues with use of parenthesis rather than brackets. – j_b Jan 13 '22 at 14:34
  • Yeah. I changed the brackets and removed extra space, still my script is failing in both scenarios. – gamer_rulez Jan 13 '22 at 15:14
  • 1
    `$(( foo ? bar : baz ))` works only for **math**, not for strings. – Charles Duffy Jan 13 '22 at 16:40

1 Answers1

1
if (${env} == "qa"); then
  ip_addr = "x.x.x.47"
else
  ip_addr = "x.x.x.53"
fi

Firstly, what is intended to be the if condition, is actually the request to run ${env} == "qa" in a subshell. This does not make sense. You need to use double bracket notation, or the test builtin. The former looks like:

if [[ ${env} == "qa" ]]

Secondly, no spaces are allowed between variable, equal sign, and value in assignments. It must read:

ip_addr="x.x.x.47"

The complete if looks like this:

if [[ ${env} == "qa" ]]; then
  ip_addr="x.x.x.47"
else
  ip_addr="x.x.x.53"
fi
phunsoft
  • 2,674
  • 1
  • 11
  • 22