I have a variable that stores the output of netcat
var=$(echo "flush_all" | nc localhost 111)
echo $var # outputs "OK"
if test "$var" != "OK"; then
    echo "failed"
    exit
fi
it outputs that it passed but when I want to programmatically check it is true, it fails. What is wrong with my comparison?
When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.
With bash, you can use == operator. Otherwize you may use -eq -lt -gt for equals, lowerthan, greaterthan.
The not equal function in Ubuntu bash is denoted by the symbol “-ne,” which would be the initial character of “not equal.” Also included is the “! =” operator that is used to indicate the not equal condition.
It seems that the variable contains a carriage return from the command substitution.  You have a couple of options.  Ensure that the string starts with OK:
if [[ "$var" == "OK"* ]]; then
or, strip the CR during the variable assignment:
var=$(echo "flush_all" | nc localhost 111 | tr -d '\r')
You could use od to figure what a variable contains.  In the example below, the variable var contains OK\r which would appear as OK when trying to echo the variable.
$ echo "$var" | od -x
0000000 4b4f 0a0d
0000004
$ echo OK | od -x
0000000 4b4f 000a
0000003
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With