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

Re: Temporary variable compatibility



On Tue, Mar 21, 2023, at 8:21 PM, Felipe Contreras wrote:
> I found a discrepancy between different shells:
>
>   f() { echo $var; }
>   var=1 f
>   test -z "${var-}"
>
> Both zsh, bash, and dash set the variable temporarily, but ksh does not.
>
> In zsh the emulation of ksh and sh both keep the variable assignment.
>
> Is this the POSIX standard?

POSIX.1-2017 leaves it unspecified, so both behaviors are conformant.
As per section 2.9.1 "Simple Commands" (e.g., something like "var=val
cmd"):

	- If the command name is a function that is not a standard
	  utility implemented as a function, variable assignments
	  shall affect the current execution environment during the
	  execution of the function.  It is unspecified:

		- Whether or not the variable assignments persist
		  after the completion of the function
		- Whether or not the variables gain the export
		  attribute during the execution of the function
		- Whether or not export attributes gained as a
		  result of the variable assignments persist after
		  the completion of the function (if variable
		  assignments persist after the completion of the
		  function)

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01


> If so, then how should one temporarily set a variable? A subshell?

That's probably the most portable approach, yes.


-- 
vq




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