bash中的字符串比较不起作用

Reu*_*ben 6 bash shell

嗨,我是bash脚本的新手.刚刚编写了这个简单的程序,但它正在抛出错误.

#!/bin/bash
os=`uname -o`
echo $os
if ["$os"=="GNU/Linux"] ; then
    echo "Linux"
else
    echo "Windows"
fi 
Run Code Online (Sandbox Code Playgroud)

使用==或-eq两种情况我得到以下错误,它正在打印else condn.

./ostype.sh:line 3:[GNU/Linux == GNU/Linux]:没有这样的文件或目录

视窗

Bash版本:GNU bash,版本3.2.48(1)-release(x86_64-suse-linux-gnu)

yid*_*ing 24

尝试

if [ "$os" = "GNU/Linux" ]
Run Code Online (Sandbox Code Playgroud)

注意空格和单一=.

[ 实际上是一个程序,其余的都是参数!

  • +1 [实际上是一个程序,其余的都是参数!`..许多人不知道它.几个月前我甚至都不知道.:-) (3认同)
  • @anishsane,你是对的.见`type -a\[` (2认同)

Sha*_*hin 7

使用=的字符串比较.请参阅:http://tldp.org/LDP/abs/html/comparison-ops.html

此外,方括号和比较运算符周围应该有一个空格,即

if [ "$os" = "GNU/Linux" ]; then 
  ^ ^     ^ ^           ^  
  | |     | |           |
   \-\-----\-\-----------\-- (need spaces here)
Run Code Online (Sandbox Code Playgroud)