help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Conditional expression evaluation using [ and [[ with -e


From: Bob Proulx
Subject: Re: [Help-bash] Conditional expression evaluation using [ and [[ with -eq operator
Date: Sun, 17 Nov 2013 00:27:23 -0700
User-agent: Mutt/1.5.21 (2010-09-15)

Greg Wooledge wrote:
> Peggy Russell wrote:
> > declare var='a'
> > 
> > if [ "$var" -eq "$var" ]; then

First, I would never do that.  I would call that very buggy.

Note that it has to behave like the standalone command.  Because way
back in before the beginning of time it wasn't a shell built-in.  On
current GNU/Linux systems the standalone command resides in coreutils
and isn't a part of any of the shells.  (Not bash, nor zsh, nor ksh,
nor others.)  Could still be invoked standalone such as through
'find'.  (But that would be silly.)

  $ /usr/bin/[ "" -eq "" ]
  /usr/bin/[: invalid integer ‘’

It is a standalone.  And so argument handling has to remain compatible
as if it were.  Even though it is now built into the shell the shell
has to handle it just the same as if it were an external command.
That is why quoting is so important for [ ... ].  But since [[ ... ]]
is and always was completely internal to the shell it doesn't require
the same quoting and therfore it doesn't.

> My personal recommendation would be: don't use -eq, ever.  It blows
> up if the arguments aren't integers.  If they are integers, it acts
> just like =.  So, there's really no reason not to use = in the first
> place.

What about this case?  This can occur when people pad numbers to a
fixed field width.

  $ [ "00" -eq "0" ] && echo yes || echo no
  yes

  $ [ "00" = "0" ] && echo yes || echo no
  no

Or this one?  These kinds of things can occur with different 'wc'
implementations that provide leading spaces or not.

  $ [ " 0" -eq "0" ] && echo yes || echo no
  yes

  $ [ " 0" = "0" ] && echo yes || echo no
  no

Of course there are many ways to do this completely differently too.

> I consider it one of the things that POSIX and backward compatibilty
> require Bash to implement, but which should be considered deprecated
> for purposes of writing new scripts.

I think -eq still has its uses.  But as with most things it really
depends upon what you want and the case you are handling at that
time.  Like mom says, "Never say never." :-)

Bob



reply via email to

[Prev in Thread] Current Thread [Next in Thread]