unixcommand-linefindetcpasswd

Unix [Homework]: Get a list of /home/user/ directories in /etc/passwd


I'm very new to Unix, and currently taking a class learning the basics of the system and its commands.

I'm looking for a single command line to list off all of the user home directories in alphabetical order from the /etc/passwd directory. This applies only to the home directories, and not the contents within them. There should be no duplicate entries. I've tried many permutations of commands such as the following:

sort -d | find /etc/passwd /home/* -type -d | uniq | less

I've tried using -path, -name, removing -type, using -prune, and changing the search pattern to things like /home/*/$, but haven't gotten good results once. At best I can get a list of my own directory (complete with every directory inside it, which is bad), and the directories of the other students on the server (without the contained directories, which is good). I just can't get it to display the /home/user directories and nothing else for my own account.

Many thanks in advance.


Solution

  • /etc/passwd is a file. the home directory is usually at field/column 6, where ":" is the delimiter. When you are dealing with file structure that has distinct characters as delimiters, you should use a tool that can break your data down into smaller chunks for easier manipulation using fields and field delimiters. awk/cut etc, even using the shell with IFS variable set can do the job. eg

    awk -F":" '{print $6}' /etc/passwd | sort
    
    cut -d":" -f6 /etc/passwd |sort
    

    using the shell to read the file

    while IFS=":" read -r a b c d e home_dir g 
    do 
      echo $home_dir
    done < /etc/passwd | sort