up vote 6 down vote favorite
share [g+] share [fb]

Maybe not programming related, but I want to reference this directory in c program.

I thought it is $HOME, but when I unset $HOME, I can still cd ~/ in bash.

It is also not $USER's home, since I can be root with USER="another", but the “~/" still point to "/root".

so how bash explains this "~/"?.

link|improve this question

not programming related... – user8885 Sep 17 '09 at 9:08
feedback

migrated from stackoverflow.com Sep 17 '09 at 9:09

This question came from our site for professional and enthusiast programmers.

5 Answers

up vote 2 down vote accepted

Maybe not programming related, but I want to reference this directory in c program.

If you try to opendir the string literal "~/" in C, you'll find it doesn't exist. It is a Bash/Csh shorthand notation that is expanded by the shell to the home directory. It does not exist as such on the filesystem and so a C program will fail- unless it invokes Bash, for example, and allows Bash to expand the string.

link|improve this answer
feedback

Using home dir information from /etc/passwd (6th field).

link|improve this answer
4  
No, don't do this. Use (in shell) getent passwd, or in C, getpwent(3). Both will succeed on NIS or LDAP systems where /etc/passwd will fail you. – kmarsh Oct 2 '09 at 16:01
feedback

It is $HOME, but changing it's value will not effect expansion. See this link for more information.

link|improve this answer
Changing its value will, but unsetting it won't. When $HOME is unset, bash sets it while expanding ~, as can be checked by running strace echo ~ On Cygwin I see this line: 79 56614 [main] echo 2380 cygheap_user::ontherange: Set HOME (from /etc/passwd) to /cygdrive/g – reinierpost Sep 17 '09 at 10:04
feedback

~ is interpreted as home-dir by the shell. it's a "keyword"

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.