skip to Main Content

I know this sounds silly, but had a rough start in this week and i’m not able to think clearly.

I’m writing this simple piece of code, which is suppose to get little complex later on. However I’m stuck near this simple If condition statement.

I wrote the code in VS on my host Ubuntu, copied it to a file inside a docker container and executed it.

As you see, the left side of the IF condition is taken as a null value for comparision. Where am i going wrong ?

#!/bin/bash

someEquation()
{
    cluster_state=`src/redis-cli -h 127.0.0.1 -p 36000 cluster info | grep cluster_state | awk -F':' '{print$2}'`
    if [[ " ${cluster_state} " == "fail" ]]; then
        echo "arr contains fail"
    fi
}

someEquation

Output:

+ someEquation
++ src/redis-cli -h 127.0.0.1 -p 36000 cluster info
++ grep cluster_state
++ awk -F: '{print$2}'
+ cluster_state=$'failr'
  == fail ]]

2

Answers


  1. By seeing OP’s attempt editing/improving OP’s code here.

    • I have attached logic of removing control m chars with your logic here.
    • Also when we are using awk we need not to use grep with it so I removed it too, as an improvement. But fair warning haven’t tested it should work but.
    • as per Barmar sir’s comments removed spaces from variable else it will give wrong results.
    • Changed backtick to $(....) too for saving command’s value to a variable.
    someEquation()
    {
        cluster_state=$(src/redis-cli -h 127.0.0.1 -p 36000 cluster info | awk -F':' '/cluster_state/{gsub(/r/,"",$2);print $2}')
        if [[ "${cluster_state}" == "fail" ]]; then
            echo "arr contains fail"
        fi
    }
    
    someEquation
    
    Login or Signup to reply.
  2. If variable cluster_state always has a trailing carriage return (hex: 0d), remove last character from variable before comparison:

    [[ "${cluster_state%?}" == "fail" ]]
    

    or add a carriage return on the other side:

    [[ "${cluster_state}" == "fail"$'r' ]]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search