Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > gnu.bash.bug > #16021

Re: numerical comparison missing in bash and expr

From "Joseph A. Russo" <jarusso@rochester.rr.com>
Newsgroups gnu.bash.bug
Subject Re: numerical comparison missing in bash and expr
Date 2020-03-11 09:38 -0400
Message-ID <mailman.2467.1583933949.2412.bug-bash@gnu.org> (permalink)
References <bb02976e-6a47-57eb-9cb4-ba25cfd2855b@rochester.rr.com> <20200311132424.GD845@eeg.ccf.org> <98561a3f-d023-eb90-031b-2d2731b12dcd@rochester.rr.com>

Show all headers | View raw


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.

Back to gnu.bash.bug | Previous | Next | Find similar


Thread

Re: numerical comparison missing in bash and expr "Joseph A. Russo" <jarusso@rochester.rr.com> - 2020-03-11 09:38 -0400

csiph-web