-4
$ bash --norc
$ export | grep '_='
declare -x _="/bin/bash"
$ export | grep '_='
$ 

What happens to _? Is it dropped out of the environment immediately when?

This is related to my other question, "why can't `_` be exported to the environment of bash?".

Kusalananda
  • 333,661
Tim
  • 101,790
  • Not actually duplicate. different questions. – Tim Apr 12 '18 at 11:56
  • I will delete the second part of the question (which is a duplicate) and try to re-open. – Kusalananda Apr 12 '18 at 12:02
  • The reason I linked the other post, is that I and anyone else will not forget to read them both and get a fuller understanding any time in the future – Tim Apr 12 '18 at 12:06

1 Answers1

2

In Bash, _ is a special parameter which is set to the value of the last argument every time a command is parsed. It also has the special property of not being exportable, which is enforced every time a command is executed (see bind_lastarg in the Bash source code).

When you start Bash using bash --norc, you get to the prompt without having executed any command; so _, if it was present in the environment, has not been overwritten. When you start Bash from Bash, the parent Bash sets _ to the command being run in the child’s environment before starting it; like any other variable present in the environment at startup, _ therefore ends up being an exported variable, and since no command has been run, that variable hasn’t been “unexported”. This explains why your first export contains it.

As soon as you run a command (your first export in this case), _ is overwritten and loses its exported flag. This explains why your second export doesn’t show it.

(Internally, _ is a variable like any other; so it can be set read-only or marked as an integer, with amusing results.)

Stephen Kitt
  • 434,908
  • Thanks. Normally, when we reassign a value to an environment parameter, the parameter remains in the environment but with a different value. So what makes _ not behave like that? – Tim Apr 12 '18 at 12:27
  • when starting bash --norc, _ is in the environment of the new shell, so it has the exported flag. But it also has the property of not being exportable. How can I check both exported flag and non-explorable property? Do they co-exist on _ all the time? – Tim Apr 12 '18 at 12:57
  • See my updates. – Stephen Kitt Apr 12 '18 at 12:59
  • Does the same thing happen to other parameters, besides _ ? – Tim Apr 12 '18 at 13:08
  • No; other parameters aren’t variables anyway. – Stephen Kitt Apr 12 '18 at 13:15
  • "It also has the special property of not being exportable, which is enforced every time a command is executed". When a bash process executes a command, if bash doesn't add _ to its own environment, why does it need to drop it from its own environment? (That is also the motivation of my new post) – Tim Apr 12 '18 at 21:10