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/
Please refer all article related questions to:

You may also be interested in: