Discussion:
Basta: protecting $_ variable.
(too old to reply)
Kaz Kylheku
2024-04-10 05:29:34 UTC
Permalink
Hi all,

In the constext of the Basta project https://www.kylheku.com/cgit/basta/
it came to my attention that the background interrupt was clobbering the
occasionally useful $_ variable which holds the last argument of the
previous command.

This was introduced in the Korn shell; Bash has it.

After some failed experiments, I worked out a stable trick for
protecting it.

You cannot simply save $_ into a local variable on entry into your trap
handler, and restore it at the end because Bash clobbers it afterward,
when the trap command finishes executing. $_ ends up with the last
argument of the trap command.

The trap setup for catching the SIGWINCH and SIGALRM signals now looks
like this:

trap 'basta_uln_save=$_; basta.update_status; : "$basta_uln_save"' ALRM WINCH

instead of just

trap basta.update_status ALRM WINCH

The first command of the sequence saves $_ into a global basta_uln_save.

The last command is the null command

: "$basta_uln_save"

You can see how that works. Bash executes the null command, expanding
the quoted parameter to form the rightmost argument, and that argument
becomes the value of $_. Mission accomplished!

I now see a stable value of $_ at the prompt, in spite of the
periodic interrupt that refreshes the status line.
--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal
Mastodon: @***@mstdn.ca
Janis Papanagnou
2024-04-10 06:26:42 UTC
Permalink
Post by Kaz Kylheku
[...]
The trap setup for catching the SIGWINCH and SIGALRM signals now looks
trap 'basta_uln_save=$_; basta.update_status; : "$basta_uln_save"' ALRM WINCH
instead of just
trap basta.update_status ALRM WINCH
I know that this looks like a hack, but since 'update_status' needs no
arguments you could also more simply just write...?

trap 'basta.update_status "$_"' ALRM WINCH

(Not sure whether introducing a global variable and supplementary code
or this hack is "better". Just mentioning it for a possible variant.)

Janis
Post by Kaz Kylheku
[...]
Kaz Kylheku
2024-04-10 13:26:47 UTC
Permalink
Post by Janis Papanagnou
Post by Kaz Kylheku
[...]
The trap setup for catching the SIGWINCH and SIGALRM signals now looks
trap 'basta_uln_save=$_; basta.update_status; : "$basta_uln_save"' ALRM WINCH
instead of just
trap basta.update_status ALRM WINCH
I know that this looks like a hack, but since 'update_status' needs no
arguments you could also more simply just write...?
trap 'basta.update_status "$_"' ALRM WINCH
(Not sure whether introducing a global variable and supplementary code
or this hack is "better". Just mentioning it for a possible variant.)
Nice streamlining; I changed to this.

One command, and no extra variable is better.
--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal
Mastodon: @***@mstdn.ca
Loading...