使用 shell 脚本在 url 中传递 "ip_addr" 时遇到问题

Facing issue while passing "ip_addr" in url using shell script

我正在尝试传递 ip_addr(如果 env = qa,则传递此 ip_addr=x.x.x.47 否则 ip_addr=x.x.x.53) 使用三元运算符并尝试使用 if 条件。 当我使用三元运算符时,我得到 operand expected (error token is ""qa"? error.And, with if condition, error: url is not calling properly如果条件失败。有人可以帮我解决这个问题吗?另外,请建议任何其他方法来解决这个问题。提前致谢!

##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}"
if (${env} == "qa"); then
  ip_addr = "x.x.x.47"
else
  ip_addr = "x.x.x.53"
fi

首先,if 条件实际上是在子 shell 中对 运行 ${env} == "qa" 的请求。这根本不符合逻辑。您需要使用双括号表示法,或内置的 test 。前者看起来像:

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

其次,不可以变量等号和[=之间允许有空格22=]value 赋值。它必须是:

ip_addr="x.x.x.47"

完整的 if 如下所示:

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