Environment variables in the Bash shell can be accessed or set using a C++ program. This is facilitated by the getnenv()
and putenv()
functions defined in the 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.
In this tutorial, you will see an example C++ script that uses getnenv()
and putenv()
functions to get and set Bash shell variables, respectively. Check out the script below to see how it is done, and then copy it to your own system and adapt it as needed.
In this tutorial you will learn:
- How to set Bash environment variables in C++ using
putenv()
- How to get Bash environment variables in C++ using
getnenv()
- Example C++ script that can get and set Bash variables

Category | Requirements, Conventions or Software Version Used |
---|---|
System | Any Linux distro |
Software | g++ or any C++ compiler |
Other | Privileged access to your Linux system as root or via the sudo command. |
Conventions |
# – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command$ – requires given linux commands to be executed as a regular non-privileged user |
Set and Get environmental shell variable using c++
- First, copy the following code to a new file. This example shows how to get and print two environment variables, and how to set one.
#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; }
Save as
shell_env.cpp
- Now let’s try to export new shell environment variable
MYENV
:$ export MYENV=linuxconfig.org
- Compile your C++ program with g++ or any other compiler you want:
$ g++ shell_env.cpp -o shell_env
- Next, let’s run our compiled script:
$ ./shell_env
Your output should be:
SHELL = /bin/bash MYENV = linuxconfig.org TEMP = /my/new/temp/path/
As you can see, our script was able to retrieve a preset environment variable SHELL
, as well as an environment variable MYENV
that we manually set ourselves. Lastly, we were able to set the TEMP
environment variable within the C++ program itself.
Closing Thoughts
In this tutorial, we saw how to set and get Bash environment variables using a C++ program on a Linux system. As seen here, the
getnenv()
and putenv()
functions allow us to get and set environment variables in Bash, respectively. Relying on environment variables is a viable way to make your C++ script cross compatible with many different systems which could have different configurations from one another.