Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison in bash is not working

Tags:

bash

shell

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)

like image 780
Reuben Avatar asked Dec 19 '12 09:12

Reuben


People also ask

How do I compare two strings in Bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

What is == in bash script?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.

Can you use && in Bash?

The Bash logical (&&) operator is one of the most useful commands that can be used in multiple ways, like you can use in the conditional statement or execute multiple commands simultaneously.


2 Answers

try

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

note the spaces, and the single =.

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

like image 177
yiding Avatar answered Oct 04 '22 00:10

yiding


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)
like image 32
Shawn Chin Avatar answered Oct 04 '22 02:10

Shawn Chin