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

Re: trap question



You can think of "trap" as a delayed "eval".

The thing that you have to understand is that your string gets evaluated/expanded twice: once when the trap statement is evaluated and once each time the EXIT trap is triggered.

With your original code, when the trap statement is evaluated, the first argument of trap (your string) gets expanded, like it would be for any other command. This yields the string  [[ 0 == '0' ]] && echo trap: var is: 0. The trap command records this string as the new command to execute for future EXIT traps. Thus, when an EXIT trap triggers, it will obviously always print 0 rather than the current value of the variable "var".

Now, if you use single quotes instead of double quotes, the first argument of the trap command expands to the string  [[ $var == '0' ]] && echo trap: var is: $var, which looks like a much more interesting command to execute when the EXIT trap triggers ;-)

Philippe


On Sat, Nov 26, 2022 at 2:58 AM Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
On Fri, Nov 25, 2022 at 3:25 PM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
>
> Double quotes evaluated when
> parsed, single quotes kept as literal until trap is sprung, yes?

Yes.

> wouldn't have occurred to me since I'd have expected the '$var' to
> remain un-expandable within single quotes.  Is this an exception or
> somehow to be viewed as routine?

You can think of "trap" as a delayed "eval".

> BTW, will this trap catch exiting
> errors or just proper returns?

Depends on the error.  If you have "setopt err_exit" (or err_return)
then the trap will be tripped when something returns false, but if you
have "setopt no_unset" (or use ${varname?message}) and reference a
variable that isn't set, the trap will not trip.  There are also some
circumstances where the parent shell will have done an opportunistic
"exec" of the final external command, so there's no zsh left to run
the trap (this is technically a bug, and will eventually get fixed).



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