Search code examples
shellgrepwc

script shell: To tell how many times a user is logged on


I have got the following:

count=$(who | grep $user | wc -l)
echo "$user is logged on $count times."

but it gives me the following output:
 is logged on      0 times.

what am I missing here? appreciate any help


Solution

  • You are using $user, but need $USER. Like,

    count=$(who | grep $USER | wc -l)
    echo "$USER is logged on $count times."
    

    I get

    efrisch is logged on 4 times.
    

    Another option is printf like

    printf "%s is logged on %s times.\n" $USER $(who | grep $USER | wc -l)
    

    for the same result.