84

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
86

You can use eval:

eval echo ~$USER

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

  • 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
  • Note also that if you eval echo "~$USER" you are making the assumption that $USER does not contain special characters that the shell may interpret. For example, if USER="foo\$bar", then when we eval the shell will substitute $bar into your output which is not what you want. Basically, if you take this route, you need to make sure that $USER is sane input. Most of the time it probably will be, but you should bear this in mind. – Zorawar Mar 30 '17 at 1:51
65

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 )
  • 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
13

It seems you are that user -- why not

echo $HOME

?

  • 3
    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`
0

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

  • 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.