96

I want to obtain home dir of any user with echo

echo ~puchuu
>> /home/puchuu

But I cant use variable

echo ~$USER
>> ~puchuu
echo `echo ~$USER`
>> ~puchuu
104

You can use eval:

eval echo ~$USER

But see Andrew's comment and glenn's reply below.

| improve this answer | |
  • 8
    In bash eval isn't needed it with just echo ~$username it's okay, but in sh eval is needed if is a variable – Felipe Alcacibar Nov 25 '15 at 14:23
  • This sometimes gives the wrong value, maybe the home folder of a previous account with the same username? – Andrew Dec 12 '15 at 18:28
  • @AndrewMacFie: What do you mean by "previous"? – choroba Dec 12 '15 at 18:49
  • 1
    @choroba Add a user, delete the user, then add a user with the same username. If the user's home folder is different the second time, this command gives the original home folder rather than the current one. glenn jackman's answer gives the current one. – Andrew Dec 12 '15 at 18:59
  • 1
    Can confirm that this won't work at all if you have anything other than letters and numbers in a username. The method provided by Evan Carroll & Glen Jackmans answer below appears to work at least on Ubuntu 18. E.g: $( getent passwd "john-smith" | cut -d: -f6 ) – Sk446 Nov 25 '19 at 11:33
78

This might work for you:

homedir=$( getent passwd "$USER" | cut -d: -f6 )

This will also work on users that are not you. For instance,

homedir=$( getent passwd "someotheruser" | cut -d: -f6 )
| improve this answer | |
  • This is legit, using getenv rather than assuming the location of passwd is even a step further than assuming the location of home is /home/ – Evan Carroll Dec 1 '16 at 22:19
15

It seems you are that user -- why not

echo $HOME

?

| improve this answer | |
  • 4
    This won't work if you are in a sudo'ed environment and did not pass sudo the -H or -i flags - $HOME will still be the previous (sudo'ing) user's home directory. – Asfand Qazi Jun 12 '15 at 11:32
1

I don't know if it helps, but placing the tilde outside the expression works on ZSH but not on Bash:

echo ~`echo $USER`
| improve this answer | |
0

Once you login, run cd to go to your home directory, then run pwd to print the working directory.

| improve this answer | |
  • That's not going to work; the idea here is to do this in shell script, and presumably without requiring the credentials of the user in question... – SamB Aug 27 '16 at 4:57
  • -1 for the same reason SamB mentioned. I edited your answer because I want you to see how to use Markdown formatting, and to be more concise. You also missed the much easier method, which is just echo $HOME. – wjandrea Sep 4 '16 at 22:35

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.