10

Hi I'm new to bash scripting. Just wrote this simple program but it is throwing error.

#!/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.

./ostype.sh: line 3: [GNU/Linux==GNU/Linux]: No such file or directory

Windows

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

Reuben
  • 5,556
  • 10
  • 43
  • 55
  • This question has already been answered, see this link [1] [1]: http://stackoverflow.com/questions/394230/detect-the-os-from-a-bash-script – mana Dec 19 '12 at 09:36
  • With the proper spacing `=` and `==` should both work to compare strings. `-eq` is an integer compare. – Hennes Dec 19 '12 at 09:42

3 Answers3

37

try

if [ "$os" = "GNU/Linux" ]

note the spaces, and the single =.

[ is actually a program, and the rest are arguments!

yiding
  • 3,482
  • 18
  • 17
  • 6
    +1 for `[ is actually a program, and the rest are arguments!`.. Many people do not know it. Even I didn't know few months ago. :-) – anishsane Dec 19 '12 at 13:18
  • and for all intents and purposes you probably want to use the shell builtin `[[`, which is probably faster. – yiding Dec 19 '12 at 13:19
  • 1
    Oh... I thought, `[` is also overridden by shell built-in. just like `[[` & `echo`... – anishsane Dec 19 '12 at 14:07
16

Use = for string comparison. See: 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)
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
0

You could use [[ "$os" == "GNU/Linux" ]]

Adz
  • 49
  • 1