Question

I think I may have approached this problem the wrong way and I could really use a hand here. I'm trying to print a report to the screen using awk. I want to list the users logged in and their full names next to each user. The only way I could figure it out is below, but it only shows my own info. Can I add it into a loop somehow to achieve this or did I go about it completely wrong?

This is what I have:

echo "User name"  "|"  "Full name"
echo "--------------------------"
echo -n "$USER " ; awk -v user="$USER" -F":" 'user==$1{print$5}' /etc/passwd
Was it helpful?

Solution

The $USER variable just contains your username.

You can pipe the who command to get the list of logged in users.

echo "User name"  "|"  "Full name"
echo "--------------------------"
who | while read username rest; do
    echo -n "$username " ; awk -v user="$username" -F":" 'user==$1{print$5}' /etc/passwd
done

OTHER TIPS

Whenever you find yourself writing a loop in shell to process text, you have the wrong solution.

who | awk '
BEGIN { print "User name|Full name\n--------------------------" }
NR==FNR { name[$1] = $5; next }
{ print $1, name[$1] }
' FS=":" /etc/passwd FS=" " -

Shell is just an environment from which to call tools and it has a language to sequence those calls. The shell tool to process text is awk.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top