Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: while loop grammar question



The thing about if, while, and until is that their condition is just a sequence of commands. If the last command in the sequence exits with status 0 (which is shell IPC for "success"), then the condition is considered "true"; if it exits with any other value, it's considered "false".  

The brackets are not part of the syntax of the compound statement. Sure,  [, [[, and (( look like syntax – and to be fair, [[ ... ]] and (( ... )) do alter the shell's parsing rules somewhat between the brackets – but they're really just the names of commands, which you can also run at the prompt without any if/while/until anywhere in sight. 

But the C-style for (( ... ; ... ; ... )) loop is special. For starters, you normally can't put semicolons inside a (( ... )) command; it's a syntax error. Even if you could, you don't want to just run the three expressions in sequence; you want to save the different parts of the _expression_ to run at their respective appropriate times in the loop execution. So that's why it's all one big piece that has to be parsed together, and for, unlike the other compound-introducing keywords, does not just take a sequence of commands. 

On Sun, Dec 8, 2024 at 5:42 PM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:



On 2024-12-08 12:59, Lawrence Velázquez wrote:
It does understand its own break condition.  The issue is that the
break condition -- e.g., the command whose exit status matters --
is not where you think it is.
Right, that was clear from your previous examples.  Still there is an expectation that the break condition will be where you expect it to be and it ain't.  But as you say, this isn't something that's going to catch people very often.  I must say tho that your diagnostics are a deep dive into understanding this sort of thing -- nice to be able to look under the hood.

With an
arithmetic "for" loop, the ((...)) construct is actually part of
the syntax, so there's no confusion about where the loop body begins.
Ah!  So symmetry is not to be expected.  That changes my perspective.  It looks like the while loop is not just a more 'primitive' for loop, but has it's own unique bag of tricks.  That's a quite satisfying answer -- I've tended to think of the for loop as an 'upgraded' while loop.  Thank you Sensei. 


    
As usual I'm thinking in C here.
An understandable impulse but one that does not serve you well when
thinking about shell scripting grammar.

So devilishly difficult to get over one's mother tongue!  The habits get bolted onto your mind.  I still declare all my variables.  





--
Mark J. Reed <markjreed@xxxxxxxxx>


Messages sorted by: Reverse Date, Date, Thread, Author