如何将命令输出与Shell脚本

时间:2016-03-04 12:11:26

标签: shell

我一直在努力想弄清楚如何将存储在变量中的命令的输出与Shell脚本中的另一个变量(也是字符串)的内容进行比较。 我知道它看起来像一个基本的RTFM案例,但我已经做了,而且我真的没有解决这个问题。

所以,我所拥有的代码如下,与Android相关(我使用ADB工具)和评论有助于理解它:

# 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

案例是IF比较中的字符串似乎永远不相等。

我认为错误在于对变量RES的第一个值赋值,因为也许我没有正确理解`字符意味着什么以及它返回的内容不是它看起来的样子。

我相信你们可以帮助我解决这个基本案例。

非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

你的字符串比较似乎没问题,应该可行。问题可能是字符串实际上是不同的。您可以使用以下内容检查详细差异(即在空格或某种控制字符中,如额外标签或其他内容):

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

这将为您提供以下$ 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|

将它与$ RES的十六进制转储进行比较。

相关问题