You need to get each user's home directory. If all of your users have their HOME at /home/$USER, then it's easy:
#!/usr/bin/env bash
who | cut -d' ' -f1 | sort | uniq |
while read userName; do
file="/home/$userName/public_html/pub_key.asc"
if [ -f $file ]; then
echo "$file : Exists"
else
echo "$file : Does not exist!"
fi
done
If you have users whose HOME isn't /home/$USER, such as root for example, then you need to figure out their home directory first. You can do this with getent:
#!/usr/bin/env bash
who | cut -d' ' -f1 | sort | uniq |
while read userName; do
homeDir=$(getent passwd "$userName" | cut -d: -f6)
file=public_html/pub_key.asc
if [[ -f "$homeDir"/"$file" ]]; then
echo "$file : Exists"
else
echo "$file : Does not exist!"
fi
done
The next problem is that if you don't have access to the user's HOME, the script will report that the file doesn't exist even if it does. So you could just run it as root, or you could first check if you can access the directory and complain if you don't:
#!/usr/bin/env bash
file="public_html/pub_key.asc"
who | cut -d' ' -f1 | sort | uniq |
while read userName; do
homeDir=$(getent passwd "$userName" | cut -d: -f6)
if [ -x $homeDir ]; then
if [ -f "$homeDir/$file" ]; then
echo "$file : Exists"
else
echo "$file : Does not exist!"
fi
else
echo "No read access to $homeDir!"
fi
done
whocommand to a variable named 'Files'. You're then trying to read from a variable named 'FILES'. These are different variables, because the shell is case sensitive.~/...always refers to the current user's home directory, not the one named by$file. You might want/home/$file/...or something like that. (And$fileisn't a file, it's a username, so I'd recommend renaming your variable to better match what they contain.)