Skip to content
Advertisement

Bash Scripting checking for home directories

I’m trying to create a script to check if user accounts have valid home directories.

This is what i got at the moment:

#!/bin/bash

cat /etc/passwd | awk -F: '{print $1 " " $3 " " $6 }' | while read user userid directory; do
if [ $userid -ge 1000 ] && [ ! -d "$directory ]; then
echo ${user}
fi
done

This works. I get the expected output which is the username of the account with an invalid home directory.

eg. output

student1
student2

However, I am unable to make it so that ONLY if there is no issues with the valid home directories and all of them are valid, echo “All home directories are valid”.

Advertisement

Answer

You could set a flag, and unset it if you see an invalid directory. Or you could simply check whether your loop printed anything.

You have a number of common antipatterns which you’ll want to avoid, too.

# Avoid useless use of cat
# If you are using Awk anyway,
# use it for user id comparison, too
awk -F: '$3 >= 1000 {print $1, $6 }' /etc/passwd |
# Basically always use read -r
while read -r user directory; do
    # Fix missing close quote
    if [ ! -d "$directory" ]; then
        # Quote user
        echo "$user"
    fi
done |
# If no output, print default message
grep '^' >&2 || echo "No invalid directories" >&2

A proper tool prints its diagnostic output to standard error, not standard output, so I added >&2 to the end.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement