Getenv () Linux / Ubuntu returns NULL

I am trying to get the users home directory using getenv("$HOME") , but it returns NULL. What am I doing wrong?

 int main(void) { char * path; path = getenv("$HOME"); printf ("The current path is: %s",path); return 0; } 
+4
source share
5 answers

Leave the value $ in the name of the environment variable. When used in the shell, $ not part of the name, but signals the shell that the variable name follows, and it should substitute its value.

+6
source
 getenv("PATH"); // This is what you really want 

And, optionally, compile with -Wall and end up with something like this. (Tested ...)

 #include <stdio.h> #include <stdlib.h> int main(void) { char *path; path = getenv("PATH"); if(path) printf("The current path is: %s\n", path); return 0; } 
+4
source

Shouldn't be getenv("PATH") ?

+1
source

For home directory you can use

 char* homedir = getenv("HOME"); 

or you can use

 char* homedir = NULL; struct passwd *pw = getpwuid(getuid()); if (pw) homedir = pw->pw_dir; 

For the PATH used by execvp , use getenv("PATH")

+1
source

Since HOME is an environment variable, you should not prefix the $ sign.

 char *value,name[20]; scanf("%s",name); value=getenv(name); if(value == NULL) printf("Not found"); else print("value = %s",value); 

Make sure you include unistd.h and all relevant header files.

0
source

All Articles