2016-03-04 344 views
1

我一直在努力想弄清楚如何將存儲在變量中的命令的輸出與Shell腳本中的另一個變量(也是字符串)的內容進行比較。 我知道它看起來像一個基本的RTFM案件,但我已經做了,我真的沒有解決這個問題。如何將命令輸出與Shell腳本中的字符串進行比較

所以,我有代碼如下,涉及到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 

的情況是,在弦如果比較從未像平等一樣。

我認爲這個錯誤是第一次賦值給變量RES,因爲我可能沒有正確理解'字符的意思,它返回的不是它看起來是什麼。

我敢肯定,你們可以幫助我這裏的基本情況。

非常感謝您的幫助

+0

檢查保存的stdout的確切內容。例如,有沒有(還)在您的預期字符串中的尾隨換行符? – mpez0

+0

你能告訴我們你的「簡單檢查」中兩個'echo'命令的結果嗎?更好...'echo'> $ {RES} <「'和'echo」> $ {EXPECTED} <「' – mauro

回答

1

你的字符串comparsion似乎是確定,它應該工作。可能問題在於字符串實際上是不同的。您可以檢查(在空白或某種類似額外的標籤或任何控制字符IE)通過使用類似的詳細區別:

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

這會給你$預期以下:

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進行十六進制轉儲進行徹底比較。

+1

這樣做我得到了以下結果: 對於用'grep'提取的值: '0000000 44 69 73 70 6C 61 79 20 50 6F 77 65 72 20 3A 73' '0000010 74 61 74 65 3D 46 4F 46 0D 0a' '000001a' 對於字符串手動引入: ' 0000000 44 69 73 70 6c 61 79 20 50 6f 77 65 72 3a 20 73' '0000010 74 61 74 65 3d 4f 46 46 0a' '0000019' 我們可以看到,我們有一個額外的回車,也是最後一個字符在兩個輸出中都不同。 所以,字符串比較工作,但字符串中的實際字符是不同的。我會進一步調查。 謝謝! – droca

相關問題