How to get HOME, given USER?
There is a utility which will lookup user information regardless of whether that information is stored in local files such as /etc/passwd
or in LDAP or some other method. It's called getent
.
In order to get user information out of it, you run getent passwd $USER
. You'll get a line back that looks like:
[jenny@sameen ~]$ getent passwd jenny
jenny:*:1001:1001:Jenny Dybedahl:/home/jenny:/usr/local/bin/bash
Now you can simply cut out the home dir from it, e.g. by using cut, like so:
[jenny@sameen ~]$ getent passwd jenny | cut -d: -f6
/home/jenny
You can use eval
to get someone's home directory.
eval echo "~$USER"
At least for local users this works for sure. I don't know if remote users like LDAP are handled with eval
.
The usual place is /home/$USER
, but that does not have to be universal.
The definitive place to search for such information is inside the file /etc/passwd
.
That file is world readable (anyone could read it), so any user has access to its contents.
If the $USER exists in the file, the entry previous to last is the user HOME directory.
This will select the entry and print the HOME directory:
awk -v FS=':' -v user="$USER" '($1==user) {print $6}' "/etc/passwd"
For more complex (remote) systems, getent is the usual command to get users information from the NSS (Name Service Switch libraries) system.
A command of
getent passwd "$USER" | cut -d : -f 6
Will provide equivalent information (if available).