blueowl
blueowl

Reputation: 35

How to get all the users from /etc/passwd which doesn't have a home directory

I am trying to get all users whose home directories are mentioned in /etc/passwd but are not present in /home.

The below code gives me all the home directories which are not present in /home but are present in /etc/passwd.

cut -d":" -f6 /etc/passwd | grep home | sort | 
    while read dir; do [ -e "$dir" ] || echo Missing $dir; done 

How do I get the list of corresponding users from the first column and create the corresponding /home directory using mkhomedir_helper(user) one by one from the list?

Upvotes: 1

Views: 972

Answers (2)

Léa Gris
Léa Gris

Reputation: 19545

Other implementation of Barmar's solution:

getent passwd | sort -t: -k6 | while IFS=: read -r u _ _ _ _ d _
do
  if [[ "$d" =~ ^/home/ ]] && ! [[ -d "$d" ]]
    then printf 'Directory %q missing for user: %q\n' "$d" "$u"
  fi
done

Using getent allow to pull the same data whenever it is a file or an NIS (Network Information Service).

[[ "$d" =~ ^/home/ ]] ensure the home directory starts with /home by matching it against Extended Regular Expression. ^/home/

Upvotes: 6

Barmar
Barmar

Reputation: 780723

You have to keep the username in the data that you read. You don't need to use cut, read can split the input into fields and assign them to variables.

grep /home/ /etc/passwd | sort -t: -k6 | while IFS=: read -r username _ _ _ _ dir _
do
    if ! [ -d "$dir" ]
    then 
        echo "Username $username missing $dir"
        mkhomedir_helper "$username"
    fi
done

Upvotes: 2

Related Questions