-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?".

3
  • Not actually duplicate. different questions. Commented Apr 12, 2018 at 11:56
  • I will delete the second part of the question (which is a duplicate) and try to re-open. Commented Apr 12, 2018 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 Commented Apr 12, 2018 at 12:06

1 Answer 1

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.)

6
  • 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? Commented Apr 12, 2018 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? Commented Apr 12, 2018 at 12:57
  • See my updates. Commented Apr 12, 2018 at 12:59
  • Does the same thing happen to other parameters, besides _ ? Commented Apr 12, 2018 at 13:08
  • No; other parameters aren’t variables anyway. Commented Apr 12, 2018 at 13:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.