droca
droca

Reputation: 45

How to compare a command output with a string in Shell Script

I've been struggling trying to figure out how to compare the output of a command stored in a variable with the content of another variable, also a string, in Shell Script. I know that it looks like a basic RTFM case but I already did and I'm really failing at solving this problem.

So, the code that I have is the following, related to Android (I'm using the ADB tool) and with comments to help understand it:

# Using the ` char to execute the command and return the result as a string
# To store it in the variable
RES=`adb shell dumpsys power | grep "Display Power"`

# Store the string in the variable
EXPECTED='Display Power: state=OFF'

#Simple checks, both returning "Display Power: state=OFF" (without quotes) in the console
echo "$RES"
echo "$EXPECTED"


# Compare if the values of the variables, both strings, are equal
# If so, perform action
if [ "$EXPECTED" = "$RES" ]
    then
        echo "inside"
        adb shell input keyevent 26
    fi

The case is that the strings in the IF comparison never seem to be equal.

I think that the mistake is in the first value assignation to the variable RES, because maybe I didn't understood correctly what the ` character means and what does it return is not what it seems to be.

I'm sure you guys can help me here with this basic case.

Thank you very much for your help

Upvotes: 1

Views: 4669

Answers (1)

GreyCat
GreyCat

Reputation: 17104

Your string comparsion seems to be ok, it should work. Probably the problem is that the strings are actually different. You can check detailed differences (i.e. in whitespace or in some sort of control characters like extra tabs or whatever) by using something like:

echo -n "$RES" | hd
echo -n "$EXPECTED" | hd

This will give you the following for $EXPECTED:

00000000  44 69 73 70 6c 61 79 20  50 6f 77 65 72 3a 20 73  |Display Power: s|
00000010  74 61 74 65 3d 4f 46 46                           |tate=OFF|

Compare it throughly with hex dump for $RES.

Upvotes: 1

Related Questions