help-bash
[Top][All Lists]
Advanced

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

Re: Undocumented behaviour of 'set -u' - errors when variable IS defined


From: Chet Ramey
Subject: Re: Undocumented behaviour of 'set -u' - errors when variable IS defined but non-number is used in numeric comparisons
Date: Fri, 15 Nov 2024 15:03:10 -0500
User-agent: Mozilla Thunderbird

On 11/15/24 1:07 PM, Sabin p wrote:
Hello. Is anyone able to explain why set -u causes the snippet below to
error out as if var was just not set?

Yes.

The intended behaviour is for "$var" -gt 0 to just resolve to false if $var
is NaN, like it does when the set -u line is cleared.

You should think about it step-by-step. I think if you do, you'll figure
out how to get the behavior you want.


if [[ "$var" -gt 0 ]]; then

1. All the words in the conditional command undergo the expansions listed
   in the man page. That means the [[ command sees

        [[ not_a_number -gt 0 ]]

   when it goes to evaluate the conditional expression.

2. When used with [[, the operands to the arithmetic operators are
   evaluated as arithmetic expressions. This is documented in the
   CONDITIONAL EXPRESSIONS section of the man page.

3. When not_a_number is evaluated as an expression, the `-u' setting
   kicks in because it's treated as a variable. This is documented
   under ARITHMETIC EVALUATION.

With that, it should be reasonably clear how to achieve what you want.

--
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/

Attachment: OpenPGP_signature.asc
Description: OpenPGP digital signature


reply via email to

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