help-bash
[Top][All Lists]
Advanced

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

Re: confusing syntax error using <= within [[ ]]


From: Martin D Kealey
Subject: Re: confusing syntax error using <= within [[ ]]
Date: Wed, 8 Oct 2025 09:37:26 +1000

On Tue, 7 Oct 2025, 21:14 Greg Wooledge, <greg@wooledge.org> wrote:

> On Tue, Oct 07, 2025 at 20:53:14 +1000, Martin D Kealey wrote:
> > if [[ -n $a$b ]] && (( c <= d )) && { [[ -n $a ]] || (( c == d )) }
> then echo ok ; else echo no ; fi
>
> Needs a ; before the closing }.


(I did run it before posting, without adding newlines or semicolons.)

Both [[…]] and ((…)) are parsed as compound commands even if they're not
described as such; meaning they have their own closing tokens so they don't
need an additional semicolon.

If this isn't documented then it should be.

Also, I'm not sure you've translated the logic correctly.


I rearranged it to something equivalent:

   - [[ $a ]] || [[ $b ]] can be rewritten [[ $a$b ]]
    from which it follows that [[ ! $b ]] can be rewritten as [[ $a$b ]] &&
   [[ $a ]]
   - ((c == d)) can be rewritten as ((c <= d)) && ((c == d))
   - then just apply normal algebraic commutative and distributive rules


Personally, I would've rewritten it with "elif":
>
>     ok=0
>     if [[ $a ]] && ((c <= d)); then
>         ok=1
>     elif [[ $b ]] && ((c == d)); then
>         ok=1
>     fi
>     if ((ok)); then echo ok; else echo no; fi
>
> Readability is important to me.
>

Hmm, why fiddle with an extra flag when one can get the same visual
improvement without it?

if { [[ $a ]] && ((c <= d)) } ||
   { [[ $b ]] && ((c == d)) }
then echo ok
else echo no
fi

or even:

if (( ${#a} && c <= d
   || ${#b} && c == d ))
then echo ok
else echo no
fi

(NB: ((…)) honors C's precedence rule for && vs ||.)

  Also acceptable would be:
>
>     ok=false
>     ok=true
>     if "$ok"; then ...
>

I find it helpful to start with

readonly true=1 false=0

And then write

foo=true
…
if ((foo)) …

(This is noticeably faster than «if "$foo";», and it won't get screwed up
by foo=exit or foo=reboot.)

-Martin


reply via email to

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