In this post, we will be discussing environment variables and how they work. An environment variable is a variable that communicates to programs how the machine is set up and sometimes controls the behavior of programs. Each variable has a name and a value. By convention, the names are all uppercase, and the values are strings that can be anything you want them to be.
To get started, open up your terminal. If you are on Linux, macOS, or any other UNIX-style OS, just type “env,” and a bunch of variables will print out. This is what we refer to as the environment. If you are on Windows, it’s a little trickier. You’ll need to go to the control panel and navigate to the environment variables section. Each variable has a name and a value, and the point of these variables is to communicate to programs how the machine is set up and sometimes control the behavior of programs.
One useful variable is the path variable. This one tells your computer where to look for executable programs. If you put your program in any of these directories, you can run it from anywhere without typing the path to the program. If a C program wants to read an environment variable, it can use the getenv function. Just pass in the variable name you want, and you’ll get null if it isn’t set and a pointer to the value if it is.
Now, let’s talk about how to set an environment variable. If you’re in the terminal, you can set it on the command line before running a program. This will set the variable just for that program. If you want to set it for the entire terminal session, then use export. The variable will be set for every program that runs in that terminal session. You can use the unset command to unset the variable if you decide that your use of export was a bit hasty.
If you’re inside your program, you can set a variable using setenv or putenv. Both do roughly the same thing, but they’re just called slightly differently. Keep in mind that this just sets the variable for this program and any child processes that it creates after this program runs.
That’s pretty much all you need to know about environment variables. They are essential for communicating and controlling programs and taking advantage of information that’s right there in your terminal. I hope this post helps you make more sense of some of the things that go on in the terminal.