PDA

View Full Version : how to get current user home directory



George2
05-06-2007, 05:21 AM
Hello everyone,


How to use Linux API to get current user home directory, e.g. for user foo, the home directory is /home/foo, for user root, the home directory is /root.


thanks in advance,
George

Salem
05-06-2007, 05:50 AM
http://opengroup.org/onlinepubs/007908799/xsh/pwd.h.html

brewbuck
05-06-2007, 04:42 PM
http://opengroup.org/onlinepubs/007908799/xsh/pwd.h.html

It's usually better to look at the HOME environment variable first. Only if that isn't set, then check the passwd file. Unless you have some specific reason for not believing/trusting the HOME variable (some security consideration) you should use it.

jim mcnamara
05-08-2007, 02:11 PM
I agree completely with Salem. Rather than argue, assume there may be very good reasons to reconsider using HOME or other environment variables for a lot of things unless there is no recourse -- simply as de facto standard, good practice.

Some casual points:

env problems are a pain/impossible to diagnose after the fact. Eliminating sources of error upfront is considered good practice.

Code re-use means that "inoccuous" code is put into a different environment where it can become less so.

Consider p 211 of McConnell 'Code Complete' 2nd Ed.

brewbuck
05-08-2007, 02:46 PM
I agree completely with Salem. Rather than argue, assume there may be very good reasons to reconsider using HOME or other environment variables for a lot of things unless there is no recourse -- simply as de facto standard, good practice.

So bash is broken?



me@host:/home/dir$ export HOME=/
me@host:/home/dir$ cd
me@host:/$


I did suggest that there may be considerations in using HOME which the OP should probably look into. But ignoring HOME as standard practice pretty much means the variable shouldn't exist in the first place. If I had the book you refer to, I'd look there. Care to elaborate at all?

EDIT: And as if getpwent() could be trusted! It can't. It's a library function so it can be trivially overriden by LD_PRELOAD hacking. Seems like the whole "benefit" is non-existent.