You can store the users in an array from the who
command and then while reading the /etc/passwd
file, loop through the array to see if the user is present in the array and if so, print the entries from /etc/passwd
file in the format you desire.
Something like:
#!/bin/bash
while read -r user throw_away; do
users+=( "$user" )
done < <(who)
while IFS=: read -r f1 f2 f3 f4 f5 f6; do
for name in "${users[@]}"; do
if [[ "$name" == "$f1" ]]; then
echo "Username: $f1, UserID: $f3, FullName: $f5"
fi
done
done < /etc/passwd
We use process substitution <(..)
to pass the output of who
to first while loop
and create an array users
. Since we only need the name we use a dummy variable throwaway
to capture everything else.
In the second while loop
(I re-used most of your existing code), we check if the first field from `/etc/passwd/ file is present in our array. If so, we print the line in your desired format.
You can also also use associative arrays (bash v4.0 or later) to store users as keys. I will leave that to you for practice.