bash:在调试陷阱中保留$ _ [英] bash: preserve $_ in a DEBUG trap
问题描述
在 bash
中,手册上说 $ _
应该是最后执行的命令的最后一个参数".
In bash
, the manual says $_
should be "the last argument of the last command executed".
这是预期的行为:
$ echo 1 2 3
1 2 3
$ echo $_
3
$
在使用 DEBUG
陷阱时, $ _
是基于陷阱运行的最后一条命令(在以下示例中为 date
)比用户上次输入的命令要高:
When using a DEBUG
trap, $_
is based upon the last command run by the trap (date
in the example below) rather than the last command the user entered:
$ exec bash
$ unset PROMPT_COMMAND
$ trap date DEBUG
$ echo 1 2 3
Sat Dec 3 11:54:33 ICT 2016
1 2 3
$ echo $_
Sat Dec 3 11:54:37 ICT 2016
date
$ # User blinks in confusion and says "but I didn't just type date!"
似乎默认情况下,设置 DEBUG
陷阱会更改 $ _
的默认行为.
It seems that by default, setting a DEBUG
trap changes the default behaviour of $_
.
Interestingly, this works as expected in zsh
:
$ zsh
genesis% trap date DEBUG
genesis% echo 1 2 3
Sat Dec 3 12:18:01 ICT 2016
1 2 3
genesis% echo $_
Sat Dec 3 12:18:04 ICT 2016
3
genesis%
使用 DEBUG
陷阱时如何保存 $ _
的值?
How can I preserve the value of $_
when using a DEBUG
trap?
推荐答案
值得注意的是,执行的最后一个命令的最后一个参数"包括文字文本执行的最后一个命令",而不是用户输入的最后一个命令";bash的行为正如其文档在这方面所承诺的那样.
It's worth noting that "the last argument of the last command executed" includes the literal text "last command executed", not "last command entered by the user"; bash is behaving as its documentation promises in this respect.
但是请不要担心:除非您的陷阱曾经返回非零值(因此中止了它们之前运行的命令),否则就很容易解决:
But never mind that: Unless your traps are ever returning nonzero values (and thus aborting commands they run before), this is easy enough to work around:
trapfunc() { local old_=$1; date; : "$old_"; }
trap 'trapfunc "$_"' DEBUG
这篇关于bash:在调试陷阱中保留$ _的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!