[英]linux shell - can't compare strings with: adb shell getprop ro.product.brand
This is really odd... I can't get this test to result in true in my linux shell and I can't figure out why. 这真的很奇怪……我无法在Linux Shell中获得此测试的结果,因此我不知道为什么。
#!/bin/bash
a=$(adb shell getprop ro.product.brand)
adb shell getprop ro.product.brand
if [ "$a" == "Huawei" ]; then
echo "Success"
else
echo "Failed"
fi
The script just outputs: 该脚本仅输出:
Huawei
Failed
Whereas this script: 而此脚本:
b=$(whoami)
whoami
if [ "$b" == "amo" ]; then
echo "Success"
else
echo "Failed"
fi
...outputs: ...输出:
amo
Success
Can anyone help me understand that? 谁能帮我理解吗?
I already tried cutting away spaces or line breaks in $a by piping to cut or sed but I get the same result... 我已经尝试通过管道切割或sed来减少$ a中的空格或换行符,但是得到的结果是相同的...
I suggest this as a way to remove leading/trailing whitespace : 我建议将其作为删除前导/尾随空格的一种方法:
# Trims $1
# If $2 supplied, assigns result to variable named $2
# If $2 not present, echoes the value to stdout
trim()
{
if
[[ $1 =~ ^[[:blank:]]*(.*[^[:blank:]])[[:blank:]]*$ ]]
then
local result="${BASH_REMATCH[1]}"
else
local result="$1"
fi
if
(( $# > 1 ))
then
printf -v "$2" %s "$result"
else
printf %s "$result"
fi
}
This function uses no external program, so has low overhead. 该功能不使用外部程序,因此开销较低。
Maybe a quick explanation of the regular expression... 也许可以快速解释正则表达式...
^[[:blank:]]*(.*[^[:blank:]])[[:blank:]]*$
BASH_REMATCH
BASH_REMATCH
访问的子表达式 .*
would eat everything up until the end of the string, including trailing blanks. .*
会吃掉所有内容,直到字符串结尾,包括结尾的空格。 .*
is, on the other hand, certain to begin with a non-blank, because the greedy initial [[:blank:]]*
will only stop when encountering a non-blank. .*
一定以非空白开头,因为贪婪的首字母[[:blank:]]*
仅在遇到非空白时才会停止。 Depending on your need, you may also use [[:space:]]
instead of [[:blank:]]
(difference explained here : https://en.wikipedia.org/wiki/Regular_expression#Character_classes ). 根据您的需要,您还可以使用
[[:space:]]
而不是[[:blank:]]
(此处说明了差异: https : //en.wikipedia.org/wiki/Regular_expression#Character_classes )。 Basically, [[:blank:]]
matches tabs and spaces, and [[:space:]]
also matches newlines, carriage returns, and a few more. 基本上,
[[:blank:]]
匹配制表符和空格, [[:space:]]
也匹配换行符,回车符等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.