简体   繁体   中英

Bash IF condition with multiple conditions not giving proper result

Trying to fetch the status of the URL for sonarqube quality gate and check if the status is "OK" the condition should pass or if the status is "ERROR" then it should fail.

quality_gatesstatus=$(curl -u $SONAR_TOKEN:https://$SONAR_SERVER/api/qualitygates/project_status?projectKey=$SONAR_PROJECT_KEY\&pullRequest=$SONAR_PR_KEY | grep -Po '"status": *\K"[^"]*"')

echo $SONAR_PR_KEY

echo "Checking the Sonar Quality gate status"
if ("$quality_gatesstatus" != "OK") && ("$quality_gatesstatus" != "NONE")
then
echo "check sonar server and fix the issues: $quality_gatesstatus"
exit 1  
else
echo "Quality gate succeeded"
fi

But its not working as per the IF statement, its going always to the else condition

The line:

if ("$quality_gatesstatus" != "OK") && ("$quality_gatesstatus" != "NONE")

is evaluated as follows (not precisely, this is a heuristic):

  1. the variable $quality_gatestatus is expanded to some string, say S
  2. S is executed as a command, with the arguments != and OK
  3. If that command succeeds, then it is executed again with the arguments != and NONE . If that command succeeds then the first block of commands is executed. Otherwise, the commands in the else block are executed.

The error you are seeing is because the string S is not an executable command. Almost certainly what you actually want is:

if [ "$quality_gatesstatus" != OK ] && [ "$quality_gatesstatus" != NONE ]; then ...

but more likely you want a case statement:

case "$quality_gatesstatus" in
OK) ... ;;
NONE) ... ;;
*) ... ;;
esac

The syntax of the shell is a bit counter-intuitive. It is not if condition; then commands; fi if condition; then commands; fi if condition; then commands; fi . It is if commands; then commands; fi if commands; then commands; fi if commands; then commands; fi . In other words, when you write if [ 5 = 5 ] , the [ and ] are not part of the shell syntax. Instead, the command [ is executed with arguments 5 , = , and ] . Although [ is probably the most common command executed in an if block, it can be any set of commands, and it is common to see constructs like if grep ... or if shh ... or if curl ... . It is slightly less common to see if cmd1; cmd2; cmd3; then ... if cmd1; cmd2; cmd3; then ... if cmd1; cmd2; cmd3; then ... , but you will see it now and again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM