2

As we know, it's only possible to change the environmental variable set of a process in some time after the fork() system call and before exec(), e.g. manipulation like this is possible only from parent to child through the appropriate API.

However, when we use bash and it's export built-in, bash somehow changes the environmental variables of the current process (instance of the shell).

How this is done? Does it use some nasty hack?

  • 3
    bash is the current process; it's just changing its own memory space. – chepner Dec 31 '15 at 19:50
  • So it runs exec() over itself? – programings Dec 31 '15 at 19:51
  • No, it just needs to modify its own env array. – muru Dec 31 '15 at 19:52
3

bash is simply updating its in-memory variables. Despite the name, an environment variable is simply a shell variable whose value is copied into the environment of any child processes. When a shell instance starts, environment strings whose "name" (the part before the first =) are valid shell identifiers are used to create shell variables whose export attribute is set. When a new process is started, any shell variable with its export attribute set (whether from the environment or set later) is added to the environment of that process.

  • If they are internal shell variables with export attribute set on, why i can see the newly added environmental variables when cat /proc/self/environ using the current shell? – programings Dec 31 '15 at 20:14
  • 2
    The environment is just part of the shell's memory space initialized by its parent. – chepner Dec 31 '15 at 21:06
  • 3
    @programings Because you're looking at the environment of cat, not the environment of the shell. – Gilles Dec 31 '15 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.