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

Re: while loop grammar question



On Sat, Dec 7, 2024, at 9:48 PM, Ray Andrews wrote:
> aa=1
> # This escape test isn't captured:
> while (( aa < 10 ))
> {
>     echo $aa
>     let aa++
> }    
>
> 
> ... the for loop is fine with or without the 'do/done' construction but 
> the while loop requires it

Not quite.  It works if the left brace isn't on its own line:

	% cat /tmp/users-30115-1.zsh
	aa=1
	while ((aa <= 3)) {
		print $aa
		let 'aa++'
	}
	% zsh -f /tmp/users-30115-1.zsh
	1
	2
	3
	%


> The echo and the increment are looped over but it won't break.

The entire rest of the script after "while" is being taken as the
test, and the while loop is essentially being run without a body.
In this variation, observe that commands after { ... } are executed
too:

	% cat /tmp/users-30115-2.zsh
	aa=1
	while ((aa <= 3))
	{
		print -n "$aa "
		let 'aa++'
	}
	print foo
	% zsh -f /tmp/users-30115-2.zsh
	1 foo
	2 foo
	3 foo
	4 foo
	[...]

And in this one, observe that the loop terminates if/when the last
command in the script exits with a nonzero status:

	% cat /tmp/users-30115-3.zsh
	aa=1
	while ((aa <= 3))
	{
		print $aa
		let 'aa++'
	}
	((aa <= 5))
	% zsh -f /tmp/users-30115-3.zsh
	1
	2
	3
	4
	5
	%

I don't know whether this behavior is intentional or not.
A comparable "if" command errors out:

	% cat /tmp/users-30115-4.zsh
	if ((1))
	{
		print true
	}
	% zsh -f /tmp/users-30115-4.zsh
	/tmp/users-30115-4.zsh:5: parse error near `\n'


-- 
vq




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