So there's $PWD, $PATH, $USERNAME and all that. I've been working on my own shell and I've just today introduced environment variables. The way I'm doing it is by creating strings called pwd, path and all so when there's a command to echo, say, $PWD I tell it to print pwd. Is this the same thing bash does? I don't yet have the provision to set environment variables but I'll work on that, I guess. My main question would be where and how actual shells do it.

Another somewhat related question, how is printenv related to all this? Because printenv is a binary and it always prints the bash environment variables, not of the shell I'm currently using to run it in the first place (obviously, how would it detect the strings in my program I've set to be my path and pwd) so where does it get these from?


A shell can store environment variables in whatever way it wants. It is not really relevant. What is relevant is that the shell should be able to pass the environment to a child process (including printenv) via the execve system call.

  • Ahh, I was just gonna shift to using execve since it's an actual system call unlike the execvp I'm using but it never occurred to me that the OS's provision to pass variables is the significant thing. Thanks a lot! – GNU Geek Aug 13 '17 at 18:28

See man 7 environ. When your shell execs another process -- by any flavor of exec(3) -- that process inherits its predecessor's environment. One convenient design for your shell might be to keep two lists: of exported and non-exported shell variables. Those exported could be maintained in the shell's own environment with putenv(3) and automatically inherited by any processes your shell creates. Those not exported could be in a separate list, accessible only to the shell.

If this kind of thing is interesting to you, you may find The Linux Programming Interface by Michael Kerrisk a useful reference.

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.