I am trying to display, set & modify PATH environment variable from a C program. I am doing something like this:-
char *cmd[] = { "echo", "$PATH", (char *)0 };
if (execlp("echo", *cmd) == -1)
But I am not getting the results.
I am trying to display, set & modify PATH environment variable from a C program. I am doing something like this:-
char *cmd[] = { "echo", "$PATH", (char *)0 };
if (execlp("echo", *cmd) == -1)
But I am not getting the results.
try this:
char *cmd[] = { "$PATH", (char *)0 };
if (execlp("echo", cmd) == -1)
You should use getenv()
, there's no need to go through a shell:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("PATH='%s'\n", getenv("PATH"));
return EXIT_SUCCESS;
}
But you won't be able to change the value. Environment variables are inherited into child processes, but the child has its own copy. You can't change the shell's environment from a different program, regardless in which language it's written. You can of course change your own process' value, but that's not what you asked to do.
In the shell itself, you can change its current environment settings, but only there. This is why you need to use "source" to run shells scripts that change the environment.
If you want to display $PATH
, try this:
#include <stdlib.h>
printf("PATH: %s\n",getenv("PATH"));
if you want to modify it, use setenv()
or putenv()
.
#include <stdio.h>
#include <stdlib.h>
...
char *pPath;
pPath = getenv("PATH");
if (pPath!=NULL)
printf ("The current path is: %s",pPath);
putenv("PATH=somepath");
...
Better solutions already given, but by way of explanation; the $PATH variable is parsed and translated by the command shell, not the echo command itself. The solutions already suggested use getenv() to obtain the environment variable's value instead.
To invoke the command shell to perform this:
system( "echo $PATH" ) ;
but that solution is somewhat heavyweight since it invokes a new process and the entire command processor just to do that.