Issue
I'm trying to write a script that checks if the user (that is sent as an argument) is logged in or not. I want the answer to return 0 to the shell if the user is logged in and 1 to the shell if the user is not logged in.
But I have run into some problem. I get the message "You need to enter a user" everytime i try to run the script even if I send a user as an argument.
#!/bin/bash
function checkUser
{
status=0
for u in $(who | awk '{print $1}' | sort | uniq)
do
if [ "$u" = "$1" ]; then
status=1
fi
done
if [ "$status" = "1" ]; then
echo "$user is logged in."
exit 0
else
echo "$user is not logged in."
exit 1
fi
}
if [[ $1 -eq 0 ]] ; then
echo 'You need to enter a user'
read u
else
user=$1
fi
Solution
You have to provide following to check whether user has provide argument or not.
if [ $# -eq 0 ] ; then
$#
used for number of argument provided in command line
Your full code should look like this,
#!/bin/bash
function checkUser {
status=0
for u in $(who | awk '{print $1}' | sort | uniq)
do
if [ "$u" == "$1" ]; then
return 0
fi
done
return 1
}
if [ $# -eq 0 ] ; then
echo 'You need to enter a user'
read user
checkUser $user
ret_val=$?
else
user=$1
checkUser $user
ret_val=$?
fi
if [ $ret_val -eq 0 ]; then
echo "User Logged In"
exit 0
else
echo "User Not Logged In"
exit 1
fi
Answered By - mf_starboi_8041 Answer Checked By - Dawn Plyler (WPSolving Volunteer)