To check whether a directory exists, you want:
Code:
if [ -d "/home/$u"]; then
but that is not necessarily a good test for whether the user exists.
First, not all users have their home directory in /home. It is common practice for normal user accounts on Linux to be created with /home/$username to be their home directory, but this does not have to be the case. Special users, e.g. root, nobody, mysql, postgres, www-data, have their home directories elsewhere. The name of the home directory does not have to be the same as the username, but for normal user accounts, this is usually the case.
Second, there is nothing to prevent you having a directory in /home for a user who does not exist. Indeed, you can remove a user but leave their home directory intact.
You will get a definitive answer by grepping /etc/passwd or for example:
Code:
/usr/bin/id $u > /dev/null 2>&1
if [ $? -eq 0 ] ; then
echo valid user
fi
However, this does not tell you where their home directory is. Maybe try:
Code:
user_home=$(sh -c "echo ~$u")
if [ -d "$user_home" ] ; then
blah blah
fi
Bookmarks