简体   繁体   English

比较bash脚本中的字符串

[英]Comparing strings in bash script

./build_binaries.sh: line 43: [: ==: unary operator expected

I have this line ( line 43 ) in my bash script which looks correct to me, but it keeps throwing error. 我在我的bash script有这一行( line 43 )看起来对我来说是正确的,但它一直在抛出错误。

if [ ${platform} == "macosx" ]; then

Error: 错误:

./foo.sh: line 43: [: ==: unary operator expected

This is on OSX. 这是在OSX上。

The problem is that $platform is an empty string. 问题是$platform是一个空字符串。 The usual workaround is to put it in quotes: 通常的解决方法是将其放在引号中:

if [ "${platform}" == "macosx" ]

Example: 例:

$ unset x
$ [ $x == 3 ]
-bash: [: ==: unary operator expected
$ [ "$x" == "3" ]
$

One possibility is to use a single = . 一种可能性是使用单个= That's the classic notation. 这是经典的符号。 Some shells allow == , but others do not. 有些shell允许== ,但有些则不允许。

Also, you should enclose the ${platform} in double quotes; 另外,您应该将${platform}括在双引号中; I think that it is an empty string, and this is confusing things. 我认为这是一个空字符串,这是令人困惑的事情。

platform=
if [  $platform  == mac ]; then echo hi; else echo lo; fi
if [ "$platform" == mac ]; then echo hi; else echo lo; fi

This produces the error you're seeing on the second line. 这会产生您在第二行看到的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM