Jamil Seaidoun
Jamil Seaidoun

Reputation: 969

bash string comparison fails

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?

Upvotes: 6

Views: 6788

Answers (1)

devnull
devnull

Reputation: 123488

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

Upvotes: 15

Related Questions