Here I wrote a C program which executes hi.sh file using system call.
Here I used . ./hi.sh so I want to execute this script in the same shell
and then try to get environment variable using getenv function, but here I am getting different output from what I expected.
The hi.sh file contains
export TEST=10
return
Means when I run this hi.sh file using system call, its export TEST sets the value to 10 in same shell.
After this, I am trying to get this variable value but its given NULL value.
And if I run this script manually from console like . ./hi.sh then it works fine and I get 10 value of TEST using getenv("TEST") function.
Code:
#include <stdio.h>
int main()
{
system(". ./hi.sh");
char *errcode;
char *env = "TEST";
int errCode;
errcode = getenv(env);
printf("Value is = %s\n",errcode);
if (errcode != NULL) {
errCode =atoi(errcode);
printf("Value is = %d\n",errCode);
}
}
output :
Value is = (null)
How can I export TEST variable in program shell? If system() executes commands in different shell then how can I use C program code to get an environment variable which is exported by the shell invoked via a system() call?
As usual, the man page does explain this, but you need to read it very carefully.
In other words, system() first starts /bin/sh, and then has /bin/sh start whatever command you want to execute.
So what happens here is that the TEST variable is exported to the /bin/sh shell the system() call implicitly started, but not to the program which called system().