8

I can parse the /etc/passwd with augtool:

myuser=bob
usershome=`augtool -L -A --transform "Passwd incl /etc/passwd" print "/files/etc/passwd/$myuser/home" | sed -En 's/\/.* = (.*)/\1/p'`

...but it seems a little too convoluted.

Is there any simple, dedicated tool for displaying users'home (like usermod can be used to change it)?

  • Are you looking for a puppetized answer? – mgjk Oct 2 '14 at 13:04
  • @mgjk No, I know how to do it on puppet. In fact I need this answer to write a bootstrapping script that sets up a puppetmaster on a LXC container :-) – Adam Ryczkowski Oct 2 '14 at 13:06
15

You should never parse /etc/passwd directly. You might be on a system with remote users, in which case they won't be in /etc/passwd. The /etc/passwd file might be somewhere else. Etc.

If you need direct access to the user database, use getent.

$ getent passwd phemmer
phemmer:*:1000:4:phemmer:/home/phemmer:/bin/zsh

$ getent passwd phemmer | awk -F: '{ print $6 }'
/home/phemmer

However there is also another way that doesn't involve parsing:

$ user=phemmer
$ eval echo "~$user"
/home/phemmer

The ~ operator in the shell expands to the specified user's home directory. However we have to use the eval because expansion of the variable $user happens after expansion of ~. So by using the eval and double quotes, you're effectively expanding $user first, then calling eval echo "~phemmer".

Once you have the home directory, simple tack /.ssh on to the end.

$ sshdir="$(eval echo "~$user/.ssh")"
$ echo "$sshdir"
/home/phemmer/.ssh
  • Great answer with all the polishing that includes the awk magic (which I never truly understood) – Adam Ryczkowski Oct 2 '14 at 13:09
  • 1
    Is it always safe to assume that the sshdir will be ~/.ssh? Can that be changed by a configuration setting anywhere or is it hardcoded into ssh? – terdon Oct 2 '14 at 13:15
  • 2
    It is a default, that can be changed in /etc/ssh/ssh_config and sshd_config; at least on Ubuntu 14.04 – Adam Ryczkowski Oct 2 '14 at 13:33
4

you are looking for $myuser's home dir ?

 awk -F: -v user=$myuser '$1==user { print $6 ;}' /etc/passwd

you can use

 awk -F: -v user=$myuser '$1==user { printf "%s/.ssh\n",$6;}' /etc/passwd

to get .ssh dir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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