-5

In bash, why can't _ be exported to the environment of the shell?

$ export _
$ export | grep _=
$

output nothing. Or do I miss something?

How can I export _ into the environment?

See also here. Thanks.

Tim
  • 101,790

2 Answers2

2

$_ is a special parameter, like $1, $- etc. It happens to be implemented as a variable in Bash, but it shouldn’t be thought of as such. See the special parameters section in the Bash manual:

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.

Special parameters are not variables.

You can’t export it because Bash enforces that: every time a command is parsed, the exported flag is cleared on the _ variable.

Stephen Kitt
  • 434,908
  • Thanks. "assignment to them is not allowed." Is it also that exporting all the special parameters (not just _) is not allowed? – Tim Apr 13 '18 at 05:06
  • 1
    Special parameters are not variables, so they can’t be exported. – Stephen Kitt Apr 13 '18 at 07:09
  • _ is a special parameter, and bash can export it when executing an external executable or script. Do you mean all special parameters except _ in that case can't be exported? – Tim Apr 13 '18 at 12:44
  • 1
    No, _ is a special parameter, and special parameters aren’t exported. Bash separately places a variable named _, storing the path of the command being run, into child process’ environments when they start. I know the manual mixes everything up in the description of the _ special parameter, but it’s easier to understand (and closer to reality) to think of the _ special parameter on the one hand, and the _ variable exported to commands on the other. – Stephen Kitt Apr 13 '18 at 12:50
  • special parameter _ and variable _ can't exit at the same time, correct? – Tim Apr 13 '18 at 14:26
  • They’re different things, so in theory they could exist at the same time. – Stephen Kitt Apr 13 '18 at 15:51
1

Because $_ is a special parameter of the Bash shell, not a generic variable.

Related question: When is `_` an environment variable of a bash shell?

dr_
  • 29,602