Here is a small example on how to set and get environmental variables using getnenv() and putenv() functions defined by C/C++ stdlib.h library. Environmental variable expansion is a great feature of a Linux shell as it enables programmers and users to rely on the environment settings of each user separately. C++ getenv() will read all exported environmental variables and putenv() will set existing or create new variables. Here is a small c++ program which can do this job:

#include <stdlib.h> 
#include <iostream> 
int main() { 
// get and print shell environmental variable home 
std::cout << "SHELL = " << getenv("SHELL") << std::endl; 
std::cout << "MYENV = " << getenv("MYENV") << std::endl; 
//set new shell environmental variable using putenv 
char mypath[]="TEMP=/my/new/temp/path/"; 
putenv( mypath ); 
std::cout << "TEMP = " << getenv("TEMP") << std::endl; 
return 0; 

Now lets' try to export new shell environment variable MYENV:

$ export

Compile c++ program:

$ g++ shell_env.cpp -o shell_env


$ ./shell_env


SHELL = /bin/bash
TEMP = /my/new/temp/path/

Free Linux eBooks

Do you have the right skills?

Our IT Skills Watch page reflects an up to date IT skills demand leaning towards the Linux and Unix environment. We have considered a number of skills and operating systems.

See the result...

Go to top