在BASH中,我们可以在变量_(下划线)中赋值并显示值吗?

Deb*_*Roy 1 linux bash shell

回答以下问题: Linux 环境变量名称中的允许字符@aiden-bell 写道,以下模式在 BASH 中给出了所有允许的 shell 变量名称:[a-zA-Z_]+[a-zA-Z0-9_]*

我发现这是真的。事实上我可以export value _="Just for fun"。不幸的是,每当我打印它时,我都会得到__bp_preexec_invoke_exec

我浏览了这个线程,虽然它很有启发性,但它实际上并没有回答我的问题。不管 shell 可能对变量做$_什么,我可以将它用于我自己的方式吗?另外,究竟是__bp_preexec_invoke_exec什么?感谢致敬。

che*_*ner 5

您可以分配给特殊参数_,但 shell 也会在每个命令之后更新其值。通常,您仅将其用作不关心结果的虚拟变量,例如

while read _ second _ ; do ...; done < input.txt
Run Code Online (Sandbox Code Playgroud)

您只关心每个输入行的第二列。

从手册页:

  _      At  shell  startup,  set to the absolute pathname used to invoke
          the shell or shell script being executed as passed in the  envi-
          ronment  or  argument  list.   Subsequently, expands to the last
          argument to the previous command, after expansion.  Also set  to
          the  full  pathname  used  to  invoke  each command executed and
          placed in the environment exported to that command.  When check-
          ing  mail,  this  parameter holds the name of the mail file cur-
          rently being checked.
Run Code Online (Sandbox Code Playgroud)

  • Bash 不会绕过只读属性,因此如果您希望每个执行的命令都有一条错误消息,您可以使用 `declare -r _="value"` 阻止它被覆盖:P (2认同)