Open In App

Shell Script to Find How Many Terminals Has User Logged-In

Last Updated : 24 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Here we are going to see Find How Many Terminals Has User Logged In. Using who command to fetch the user list and then using grep command we can find the number of Terminal that the user has logged in the Linux. We can use LOGNAME or UID to identify the user. UID is a unique User ID assigned to every user that logged in the system, it is an integer value. The LOGNAME is the unique username of the user it can be alphanumeric.

We can use the following command to know the username of the current and its user ID:

For Username/LOGNAME

echo $LOGNAME

Output:

Shell Script to Find How Many Terminals Has User Logged In

Displaying username

For UID(User ID):

id -u

Here, -u represents that we are interested in user ID.

Output:

Shell Script to Find How Many Terminals Has User Logged In

Displaying user ID

Approach :

  • Taking input from Terminal
  • Check if the input is UID or LOGNAME
  • From the user list find all the numbers of Terminal that are opened via input UID.
  • Then read the passwd  file from etc directory that contains all the information about users.

Below is the implementation:

#! /bin/bash

# Taking input from user
echo "Enter LOGNAME OR UID"
read input

# checking if input is a UID or LOGNAME
if [[ $input ]] && [ $input -eq $input 2>/dev/null ]
  
  # If input is UID
  then
    echo "Number of terminals are "
    cat /etc/passwd | grep $input -c 
  
  # If input is LOGNAME
  else
        cat /etc/passwd>userlist
        echo "Number of terminals are "
        grep -c $input userlist
fi

Output:

Shell Script to Find How Many Terminals Has User Logged In

Using LOGNAME

Shell Script to Find How Many Terminals Has User Logged In

Using UID


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads