Find the answer to your Linux question:
Results 1 to 2 of 2
As part of an assignment on iteration I need to create a script that will "check every 60 seconds whether a particular user has logged on to the system. The ...
  1. #1
    Just Joined!
    Join Date
    Sep 2007
    Posts
    1

    Bash script to check if user logged on

    As part of an assignment on iteration I need to create a script that will "check every 60 seconds whether a particular user has logged on to the system. The user name is passed into the script as a command line argument".

    So far I've got ...

    Code:
    # get username
    echo "Enter username"
    read username
    
    # see if user is logged on
    who | grep $username
    
    # while exit status is false continue to check
    while [ $? != 0 ]
    do
            sleep 60
    done
    
    echo "$username has logged on"
    The problem is that if I enter a username that's isn't logged in it still gets past the while statement. I think this is because the sleep command returns a true exit status?

  2. #2
    Just Joined!
    Join Date
    Feb 2007
    Location
    pilani,india
    Posts
    4
    you are right..... while checks for $? which returns the exit status of the previous command executed...so in second iteration sleep returns 0 and $? becomes 0.
    a better solution would be
    while [ $(who | grep $username) != 0 ]
    do
    sleep 60
    done
    echo "$username logged in"

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...