I am trying to save a users home directory to a users.txt file, but I just keep saving my own. The script asks the user to enter their username, which I have saved in $username. When I run

ls ~ >> users.txt

It shows ls home/student/am1014 (which is my username)

I assume I need to use sudo to store it but I'm not sure how.

  • You can get the home directory of user from /etc/passwd file Apr 27, 2017 at 13:56
  • What do you want to save exactly? The name of the home directory or the list of files and directories it contains? Why is sudo relevant? What script asks for username? Please edit your question and clarify what you are trying to do.
    – terdon
    Apr 27, 2017 at 14:13

2 Answers 2



sudo -u joe ls ~

~ is expanded by your shell before running the command (here sudo), so in effect that runs:

sudo -u joe ls /home/me

To list the content of joe's home directory:

ls ~joe

Or if you don't have read access to his home directory:

sudo -u joe ls ~joe

Or for a shell running as joe to expand the ~:

sudo -u joe sh -c 'ls ~'

Note that except in csh/tcsh/zsh you can't use the ls ~joe approach if the name of the user is in a variable. Depending on the shell

echo ~$user

would either output /home/mejoe or ~joe. In bash, if there was a user called $user (literally), that would return his home directory.

Here you'd need:

eval "ls ~$user"

(you'd have made sure $user contains a valid user name beforehand).


The following command will read /etc/passwd and will output username : home-dir

awk -F: '{print $1":" $6}' /etc/passwd

Output will be something like:


You can redirect the output to a file using:

awk -F: '{print $1":" $6}' /etc/passwd > result.txt
  • 1
    /etc/passwd is just one of the different possible backends where the user database may be stored. See also NIS+, LDAP, mysql... On some systems, you can use getent passwd. But here, you can just use ~user to get the home directory of a given user. Apr 27, 2017 at 14:27
  • @StéphaneChazelas - thanks :) I'm aware of ~username. Since the OP ask for users, having a one line solution which provide a list of all users in the system and their directory seems the best approach.
    – Yaron
    Apr 27, 2017 at 14:32
  • @StéphaneChazelas for NIS+ running ypcat passwd | awk -F: '{print $1":" $6}' should result with the same output
    – Yaron
    Apr 27, 2017 at 14:33

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.