2
username=$1
freq=$2

checkuser()
{
  if who grep "$1"
  then
  sleep 60
  fi
}

if [ -n "$1" ]
then
echo "Enter username"
read username
checkuser
echo -e "$1 is logged on \a"
echo -e "$1 logged in at `date`">>LOG
checkuser
else
echo "User is not logged on"
fi

我需要将第二个参数集成到我的代码中,它允许用户指定脚本应该在什么时间之后检查谁登录。我目前将它设置为 60 秒,这需要是默认频率。我尝试使用其他功能但无济于事。我想到了这样的事情......

if [ "$2" -ne 0 ]
then
freq=$2
else
freq=60

感谢威廉,这非常有帮助!我稍微更改了代码并想出了这个。I now need to add a 3rd argument "X" which when selected just sends a message to the LOGFILE and not to the screen. 我做了尝试,但没有按预期进行。

 username=$1
 freq=${2:-10}
 X=$3

 checkuser()
 {
 whoami|grep "$1";
 }

 while checkuser "$username"
 do
 echo -e "$1 is logged on \a"
 echo "$1 logged in at `date`">>LOGFILE
 sleep $freq
 exit 0
 done
 echo "User is not logged in"

 if [ "$3" -ne 1 ]
 then
 echo "$1 logged in at `date`"LOGFILE
 fi
4

3 回答 3

1
username=$1
freq=${2:-60} # Set a default frequency

checkuser(){ who | grep -q "$1"; }

while ! checkuser "$username"; do
    echo "User is not logged on"    
    sleep $freq
done
echo "$1 is logged on"

另请注意,您可以简化用户名的设置:

username=${1:-$( echo "Enter username: "; read u; echo $u; )}
于 2012-11-27T14:40:36.497 回答
0

一个简单的 shell 脚本,它将用户名作为输入并确定用户当前是否登录。

if [[ $# -eq 0 ]]; then
    echo "Usage: " $0 "username"
    exit 1
fi

result="$(who | grep $1 | wc -l)"

if [[ $result -gt 0 ]]; then
    echo "$1 is currently logged in"
else
    echo "$1 is not logged in"
fi

exit 0
于 2018-04-26T04:36:22.193 回答
0
echo 'Enter id'
read id
res=`who | grep "$id" | wc -l` 
if [ $res -eq 0 ]
then
    echo 'user is not logged in'
else
    echo 'user is logged in'
fi
于 2017-01-28T14:50:05.200 回答