bug-bash
[Top][All Lists]
Advanced

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

Re: numerical comparison missing in bash and expr


From: Joseph A. Russo
Subject: Re: numerical comparison missing in bash and expr
Date: Wed, 11 Mar 2020 09:38:28 -0400
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.4.1

Hi,

Thank you

I appreciate the explanation and the prompt response.

Joe

On 3/11/20 9:24 AM, Greg Wooledge wrote:
On Wed, Mar 11, 2020 at 07:29:38AM -0400, Joseph A. Russo wrote:
# the following two lines work  
[ 5 < 10 ] && echo true || echo false
[ 5 > 10 ] && echo true || echo false
You've misunderstood the syntax here.  The < sign introduces a
redirection of standard input, from a file named "10".

What you've written is equivalent to

[ 5 ] < 10 && echo true || echo false

The command [ 5 ] tests whether the string "5" has a non-zero length.
It does, and so the command returns "true" (exit status 0).

The SECOND command uses > which introduces an output redirection, to
a file named "10".  I believe you will find there is an empty file
named "10" in your working directory now, assuming you didn't delete
it after your tests.

# the next three lines fail
n=5
[ $n < 10 ] && echo true || echo false
[ $n > 10 ] && echo true || echo false
These commands are identical to the previous set.  The only difference
is whether the file named "10" existed or not.

If these "failed", it's perhaps because you ran these commands first,
before the file existed.  And you ran the first set of commands second,
after the file was created, which suppresses the error you would have
got from the input redirection when the file was missing.

There are various correct ways to perform integer comparisons in
bash.  From oldest to newest:

test "$n" -lt 10

[ "$n" -lt 10 ]

[[ $n -lt 10 ]]

((n < 10))

The first two are POSIX compatible.  The second two are bash extensions.



reply via email to

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