4

I'm trying to write a script that will check if users (as arguments) are logged more than one time simultaneously. So far I have a script then checks the first argument and it works fine. But how do I do it to check for other users as arguments? Here is the code:

for users in $(w -h)
do    
if [ "$users" = "$1" ]
then echo "User $1 is logged in"
counter=$((counter+1))
fi
done    
if [ "$counter" > 1 ]
then echo "User $1 is logged $counter times"
else
echo "User $1 is logged less than two times"
fi

bash usersscript.sh user1 user2 user3 etc... Thanks for your help

5

To modfy your current approach, you would need an array of counters for the different users, and an additional loop to test each value of $users against each positional parameter $1, $2, ... .

Note that for users in $(w -h) loops over all the whitespace-delimited tokens in the output of w -h, not just the usernames - it may "work" (because it's unlikely that other tokens match a valid username) but it's not "right" - you could use $(w -h | cut -d ' ' -f1) to extract just the usernames.

For a simpler approach, you could run w -h for each username given on the command line, and count the number of lines of output, for example using wc -l

#!/bin/sh

for user do

  counter=$(w -h "$user" | wc -l)

  if [ "$counter" -gt 2 ]; then
    printf "user %s is logged in %d times\n" "$user" "$counter"
  else
    printf "user %s is logged in less than two times\n" "$user"
  fi

done

Note that bash is not necessary for this - you can use the lighter /bin/sh shell (although the same code will run in bash).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.