How To: Modify Bash Environment in C

This article will outline how to modify environment variables from a running C process. It should be noted that setting variables from your C process into the environment will only persist during process lifetime. Environment variables are propagated forward to a child program, but not backward to the parent.

Earlier I wrote about creating, removing, changing environment variables directing in Bash, now I will show you how to do these modifications using C.

Creating An Environment Variable In C process

Creating the environment variable can easily be achieved using the C function int setenv(const char *name, const char *value, int overwrite);. It takes two parameters, the first parameter being the name of the environment variable, and the second being a flag outlining whether to overwrite a pre-existing variable of the same name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
#include <stdlib.h>
 
int main()
{
	char *name = "DATA";
	char *value = "erik";
 
	if(setenv(name, value, 1) < 0){
		fprintf(stderr, "Could not create environment variable.\n");
		return -1;
	}
 
	fprintf(stdout, "-%s-\n", getenv("DATA"));
	return 0;
}

The variable will persist for any children you may fork, or if you execute a system call to grab the variables.

Removing An Environment Variable Using unsetenv

To remove an environment variable using your C process, you may call int unsetenv(const char *name);. Where char *name is the name from the environment. If name does not exist in the environment, then the function succeeds, and the environment is unchanged.

unsetenv(name);

Clear The Environment Using clearenv

To clear the entire environment you can:

clearenv();

Or

environ = NULL;

Reading An Environment Variable Using getenv

To just read an environment variable there is the C call, char *getenv(const char *name);. This will return the value of the environment variable.

getenv("data");

Those are the basic functions you can execute from your C process to set, remove, create those environment variables. Remember, if you want to achieve that in Bash head on over to my other article Using The Bash Shell Environment.

Leave a Reply

Your email address will not be published. Required fields are marked *


five − = 4

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>