[CALUG] Shell script question.

James Ewing Cottrell 3rd JECottrell3 at Comcast.NET
Tue May 4 16:21:31 EDT 2010


Everything said so far has been true, however, as far as I am concerned 
it completely misses the point, and illustrates one of my Pet Peeves.

*** Avoid using IF to test for String (in)equality or Patterns.
*** Use CASE instead

case "$var" in
('')	echo VAR is empty;;
(*)	echo VAR is nonempty;;
esac

This is MUCH easier to read, and you get to use Filename Globbing 
characters as well.

I prefer the extra left parenthesis to keep the emacs paren balancer 
happy. Otherwise, you need "# (" comments on the first two lines.

I don't worry about older shells much; if I was stuck on such a host, 
I'd compile my own bash, altho leaving the '(' out is certainly a 
possibility too.

Modern shells tend to treat the results of a variable as a "word", altho 
older shells may have reparsed the output. I'd still use the double 
quotes tho, just to make it explicit.

JIM

Etan Reisner wrote:
> On Wed, Mar 03, 2010 at 06:00:47PM -0500, Jim Bauer wrote:
>> Brian Debelius wrote:
> <snip>
>>>     Why would you do this:
>>>
>>> if [ "x$var" = "x" ]; then
>>> ...
>>> fi
>>>
>>>    Instead of this:
>>>
>>> if [ -z $var ]; then
>>> ...
>>> fi
>> To protect against an error if var was something like '-a'.  Most modern
>> shells don't get tripped up over things like that.  But older systems
>> would generate an error.
>>
>> And your -z version above has a bug.  Try it with var="a b".
>> Use "$var" not $var to fix it.
> 
> It also protected against issues with older shells and empty strings,
> which similarly tends not to be an issue these days.
> 
>     -Etan
> 
> _______________________________________________
> CALUG mailing list
> CALUG at unknownlamer.org
> http://lists.unknownlamer.org/listinfo/calug
> 
> 
> ------------------------------------------------------------------------
> 
> 
> No virus found in this incoming message.
> Checked by AVG - www.avg.com 
> Version: 9.0.733 / Virus Database: 271.1.1/2729 - Release Date: 03/07/10 14:34:00
> 




More information about the CALUG mailing list