How to get a user’s home directory from the username in a variables in Bash?

In Bash, ~username gives the username user’s home. However, this does not work for situations where username is in a variable such as

~$user

How to get the home directory from the user name in a variable in Bash?

You can use this Bash script snippet:

userhome=$(eval echo ~$user)

Here, $user get evaluated to its value (say VALUE) and then ~VALUE will be evaluated again by eval which gives the same effect as ~username.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

One comment:

  1. This is not the right way to get the home directory in the shell scripts. This would not fail even when there is no user with the given name available. The best way is to either user getent or by using awk to get it from the /etc/passwd file

Leave a Reply

Your email address will not be published. Required fields are marked *