Ubuntu – Take user name as input: if user is logged in, display running processes belonging to the user

bashprocessscriptsusers

I want to write a script that takes the name of a user as command line input. If that user is logged in then it will display the processes the user is running. If he/she is not logged in, then the script should mention this.

My attempt is not working:

#!/bin/bash
echo "Who are you?"
read user
echo $user
name=$(whoami)
if[$user == $name]
then
  top -u $user
else
  echo "not logged in"
fi

Best Answer

You can use the who -u command to list the users who are logged in. Then you could use grep to look for a specific user in the output, and exit with success if found, or exit with failure otherwise.

#!/bin/bash

read -p 'Enter username to check: ' user
if who -u | grep -q "^$user "; then
    top -u "$user"
else
    echo "User $user is not logged in"
fi

(Thanks to @dessert for shortening the who -u | ... part!)

Related Question