help-bash
[Top][All Lists]
Advanced

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

Re: Trick for saving and restoring $_ in trap handler.


From: Andreas Kähäri
Subject: Re: Trick for saving and restoring $_ in trap handler.
Date: Wed, 10 Apr 2024 10:02:00 +0200

On Wed, Apr 10, 2024 at 09:36:14AM +0200, alex xmb sw ratchev wrote:
> to reuse $_ u must save it , normal practice

So it is, but what Kaz shows is how to restore it, which could
potentially be tricky if you're not aware how this special variable is
handled by the shell.

What they show is that to restore $_ to the value saved in $uln_save one
can use the : utilitiy, which as no other side-effect than evaluating
its arguments (which sets $_).

Regards,

> 
> On Wed, Apr 10, 2024, 07:17 Kaz Kylheku <kaz@kylheku.com> wrote:
> 
> > Hi all,
> >
> > I have an interactive Bash environment in which a periodic
> > trap goes off for the ALRM signal.
> >
> > It has come to my attention that this interferes with the
> > value of the $_ variable; it gets spontaneously clobbered.
> >
> > You can't save it and restore it in the trap handler
> > function.
> >
> > I worked out a trick of saving it in a global variable:
> >
> >   trap 'uln_save=$_; handler; : "$uln_save"' ALRM
> >
> > I.e. the trap isn't the function directly, but a three command
> > sequence. The first is an assignment that saves the current
> > value of $_ in $uln_save. Then we call the handler.
> > After that we execute a : null command, giving it "$uln_save"
> > as the argument. When that command is executed, that argument
> > will be stuffed into $_, and our job is done.
> >
> > Cheers ...
> >
> >

-- 
Andreas (Kusalananda) Kähäri
Uppsala, Sweden

.



reply via email to

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