[plug] Simple bash scripting problem (again)

Craig Ringer craig at postnewspapers.com.au
Mon Oct 10 19:33:57 WST 2005


Timothy White wrote:

>Ok. So it's still not working! This time it's in a compare function!
>I'm almost ready to use perl!!!!
>Following examples from
>http://www.tech-recipes.com/bourne_shell_scripting_tips209.html and
>the 'info bash' pages...
>I have worked out that this is the syntax for what I want...
>if [ $var == "" ]
>then
>  echo variable is null
>fi
>
>In my script it doesn't work!!
>  
>
Please specify how it doesn't work in future. That's way better than 
having to guess.

In this case, I think you want:

if [ "$var" == "" ]; then
   echo "variable is null"
fi

or

if test "$var" = "" ; then
    echo "variable is null"
fi

Note that $var is quoted. That means that even if it's empty, it'll 
still be treated as an argument, rather than completely eliminated. It's 
the difference between:

var=""
if [ == ""] ; then echo "variable is null" ; fi

and

var=""
if [ "" == "" ] ; then echo "variable is null" ; fi

I find that it helps to think of shell commands as /text/ that is 
expanded, then interpreted. It's a very different concept to most 
programming and can be truly horrific if you misunderstand, but I find 
it's quite alright now that I'm used to it. It just means that you need 
to think very carefully about all escaping and quoting, since:

command "$arg"

and

command $arg

are two _totally_ different things.

On a side note, I find that:

set -e -u

is an extremely good thing to do in all scripts - so that your script 
will (a) abort if any command returns an error code that you don't 
handle, and (b) will treat $UNDEFINED_VARIABLE as an errror, rather than 
substituting the empty string.

--
Craig Ringer



More information about the plug mailing list