Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getenv() Linux/Ubuntu returns NULL

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

int main(void)
{
    char * path;
    path = getenv("$HOME");
    printf ("The current path is: %s",path);

    return 0;
}
like image 697
arynhard Avatar asked Jan 18 '13 18:01

arynhard


2 Answers

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

like image 100
Geoff Reedy Avatar answered Oct 16 '22 22:10

Geoff Reedy


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;
}
like image 45
DigitalRoss Avatar answered Oct 16 '22 22:10

DigitalRoss