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

2 Answers 2

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.

6
  • Thanks. "assignment to them is not allowed." Is it also that exporting all the special parameters (not just _) is not allowed? Commented Apr 13, 2018 at 5:06
  • 1
    Special parameters are not variables, so they can’t be exported. Commented Apr 13, 2018 at 7: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? Commented Apr 13, 2018 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. Commented Apr 13, 2018 at 12:50
  • special parameter _ and variable _ can't exit at the same time, correct? Commented Apr 13, 2018 at 14:26
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?

3
  • How can I export it then? Commented Apr 12, 2018 at 11:31
  • I imagine you could copy its content to a variable $FOO, then export the latter. Commented Apr 12, 2018 at 12:07
  • Does export not work with any special parameter? Where in the official document does it say so? Commented Apr 12, 2018 at 12:08

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.