Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash if statement behavior

Tags:

bash

I am missing something fundamental concerning either the bash's if construct/operators or string comparison. Consider the following script:

#!/bin/bash
baseSystem="testdir1"
testme="NA"
if [ "$baseSystem"=="$testme" ]; then
    echo "In error case"
fi
if [ "$baseSystem"!="$testme" ]; then
    echo "In error case"
fi

I get:

In error case
In error case

So it enters each case even though they should be mututally exclusive. Any help is appreciated.

like image 710
matze999 Avatar asked Feb 16 '23 05:02

matze999


1 Answers

bash happens to be somewhat particular about spaces.

Add spaces around the operators:

if [ "$baseSystem" == "$testme" ]; then

...

if [ "$baseSystem" != "$testme" ]; then

The following are not equivalent:

[ "$a"="$b" ]
[ "$a" = "$b" ]

Your first test is essentially the same as saying if [ "testdir1==NA" ]; then which would always be true.

like image 89
devnull Avatar answered Feb 26 '23 19:02

devnull