Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash string comparison fails

Tags:

bash

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?

like image 979
Jamil Seaidoun Avatar asked Apr 02 '14 07:04

Jamil Seaidoun


People also ask

How to check if 2 strings are equal in bash?

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.

How to compare in bash script?

With bash, you can use == operator. Otherwize you may use -eq -lt -gt for equals, lowerthan, greaterthan.

Is not equal to in bash?

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.


1 Answers

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
like image 117
devnull Avatar answered Oct 20 '22 16:10

devnull