I am to program a simple shell in linux that can implement various stuffs including environment variables. I tried printing these variables using getenv but I have some problems. getenv always return NULL even if the user types a correct variable like $HOME for example. Here is my code
int i = 0;
if(strcmp(cmdArgv[i], "echo") == 0){
char *variable;
for(i = 1; cmdArgv[i] != NULL; i++){
variable = getenv(cmdArgv[i]);
if(!variable){
puts("not a variable");
printf("%s ", cmdArgv[i]);
}else{
puts("a variable");
printf("%s ", variable);
}
}
printf("\n");
exit(0);
}
It doesn’t enter into the else condition. For example if the user types echo ls $HOME. This input is parsed into the cmdArgv which is a char **. Then the output I have is
not a variable
ls
not a variable
$HOME
BUT $HOME is a variable so maybe my implementation of getenv isn’t right. Any ideas as to what seem to be the problem? Thanks.
The variable is called
HOME, not$HOME. (The latter is your shell’s syntax for expanding the variable.)