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
Best Answer
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 ofw -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 usingwc -l
Note that
bash
is not necessary for this - you can use the lighter/bin/sh
shell (although the same code will run in bash).