HPE Community read-only access December 15, 2018
This is a maintenance upgrade. You will be able to read articles and posts, but not post or reply.
Hours:
Dec 15, 4:00 am to 10:00 am UTC
Dec 14, 10:00 pm CST to Dec 15, 4:00 am CST
Dec 14, 8:00 pm PST to Dec 15, 2:00 am PST
System Administration
cancel
Showing results for 
Search instead for 
Did you mean: 

Check file existence in your directory

 
calvinleung
Occasional Visitor

Check file existence in your directory

In the unix server, there shoud have a file which called abc.txt under each user directory , if I want to check if all user direcory have this file , to know which user do not have this file , what can i do ?

Thanks.

2 REPLIES
Matti_Kurkela
Honored Contributor

Re: Check file existence in your directory

You can write a small script, that uses the information in /etc/passwd to find the usernames and home directories.

 

#!/bin/sh

USERFILE=abc.txt

# from this point on, read /etc/passwd as standard input
exec </etc/passwd

while read PASSWDLINE; do
    # username is the 1st field, home directory is 6th
    USERNAME=$(echo "$PASSWDLINE" | cut -d : -f 1)
    USERHOME=$(echo "$PASSWDLINE" | cut -d : -f 6)

    # see if the specified file exists
    if [ ! -f "$USERHOME/$USERFILE" ]; then
        echo "$USERNAME does not have the file $USERHOME/$USERFILE"
    fi
done

 In general, most "check if condition X is true, for each user" problems in Unix systems can be solved by a general method of "walk through /etc/passwd one line at a time: from each line, pick the user-specific information you need, then perform the check".

MK

Re: Check file existence in your directory

># from this point on, read /etc/passwd as standard input
>exec </etc/passwd

It is probably much easier to use awk than cut(1) and not use tricky stuff like exec:

awk -F: '{print $1, $6}' /etc/passwd | while read USERNAME USERHOME; do
# username is the 1st field, home directory is 6th
# see if the specified file exists
if [ ! -f "$USERHOME/$USERFILE" ]; then
echo "$USERNAME does not have the file $USERHOME/$USERFILE"
fi
done