I’m coding a shell currently and for some reason I can’t get my printenv function to work. When a command is not given, it works. When two arguments are given, it also works. However, when one argument is given it does not work and prints nothing.
The code is as follows:
else if (strcmp(args[0], "printenv")==0){
/* Previously: if (args[1] == NULL && args[0] != NULL){ */
if (argc == 1){
int i = 0;
while (envp[i] != NULL){
printf("%s\n", envp[i++]);
}
}
/* Previously: else if (args[2] == NULL && args[1] != NULL){ */
else if (argc == 2){
char *env;
while (args[1] = *argv++){
env = getenv(args[1]);
if (env != NULL){
printf("%s", env);
}
}
free(env);
}
else {
fprintf(stderr, "%s: Too many arguments\n", args[0]);
}
}
I stopped reading here. The
strcmpcall having already determined that*args[0]=='p', why are you comparingargs[0]to NULL?Now, that that’s cleared-up. I think you don’t need this loop at all:
Just the loop body:
And as @Jason comments, you should not free (or otherwise modify) the pointer returned by
getenv(nor the data to which it points).