bash 中的字符串比较不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13949260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String comparison in bash is not working
提问by Reuben
Hi I'm new to bash scripting. Just wrote this simple program but it is throwing error.
嗨,我是 bash 脚本的新手。刚刚写了这个简单的程序,但它抛出了错误。
#!/bin/bash
os=`uname -o`
echo $os
if ["$os"=="GNU/Linux"] ; then
echo "Linux"
else
echo "Windows"
fi
Using == or -eq for both cases I'm getting the following error and it is printing the else condn.
在这两种情况下都使用 == 或 -eq 时,我收到以下错误,并且正在打印 else condn。
./ostype.sh: line 3: [GNU/Linux==GNU/Linux]: No such file or directory
./ostype.sh: 第 3 行: [GNU/Linux==GNU/Linux]: 没有那个文件或目录
Windows
视窗
Bash version : GNU bash, version 3.2.48(1)-release (x86_64-suse-linux-gnu)
Bash 版本:GNU bash,版本 3.2.48(1)-release (x86_64-suse-linux-gnu)
回答by yiding
try
尝试
if [ "$os" = "GNU/Linux" ]
note the spaces, and the single =.
注意空格和单个=.
[is actually a program, and the rest are arguments!
[实际上是一个程序,其余的都是参数!
回答by Shawn Chin
Use =for string comparison. See: http://tldp.org/LDP/abs/html/comparison-ops.html
使用=的字符串比较。请参阅:http: //tldp.org/LDP/abs/html/comparison-ops.html
Also, there should be a space around the square brackets and the comparison operator, i.e.
此外,方括号和比较运算符周围应该有一个空格,即
if [ "$os" = "GNU/Linux" ]; then
^ ^ ^ ^ ^
| | | | |
\-\-----\-\-----------\-- (need spaces here)

