首页 > 解决方案 > 我有一个登录时间的工作脚本,但如果用户未登录,我会收到错误消息

问题描述

我有一个工作脚本,它告诉用户登录了多长时间。但是如果用户没有登录,它会说他们已注销,但它会给我一个脚本中间的测试错误。

我试图弄清楚如果用户不在线如何跳过这些行

if [ $eMin -lt 0 ]
     then
     eMin=$(expr $eMin + 60 )
    eHr=$(expr $eHr - 1 )
    fi

这是上下文的完整脚本

while [ -z "$1" ]
do
echo -n "Please enter valid id: "
read var1
set $var1 $1
# Break the loop
if [ -n "$1" ]
then
break
fi
done

# Check if the user is a valid user
if id "$1" >/dev/null 2>1;
# If so, then check if he if he is currently logged on and set on/not on as variable
then
# Set full name variable based on matching ID
fullname=$(grep "$1" /etc/passwd | cut -d ':' -f5 | sort -k 2 | tr ",,:" " " | awk '{print $2,$1}')
# Get Current  Hours and Minutes
nowHr=$(date | cut -c 12,13)
nowMin=$(date | cut -c 15,16)
onHr=$(who |grep "$1" | cut -c 34,35)
onMin=$(who |grep "$1" |cut -c 37,38)
# Hours minutes spent logged on
eHr=$(expr $nowHr - $onHr )
eMin=$(expr $nowMin - $onMin )

if [ $eMin -lt 0 ]
then
eMin=$(expr $eMin + 60 )
eHr=$(expr $eHr - 1 )
fi

# Test and display user name and if curretnly logged on
# Exit with code of 0 if success and 1 if fail
who -u |grep -q "$1" || test && echo "$fullname is logged on for $eHr hour(s) and $eMin minutes(s)." &&  exit 0 || echo "$fullname is not logged on" && exit 1
# Displays if invalid id is entered
else
echo "The user you entered, $1 is not a valid user on this system"
# Exit with code of 2
fi
exit 2

错误信息是

expr: syntax error
expr: syntax error
/timeOn: line 38: [: -lt: unary operator expected
John Doe is not logged on

标签: linuxbashif-statement

解决方案


如果用户未登录,则无法获得“who | grep $1 | cut -c 37,38”的任何输出。因此,您不能将空字符串与整数进行比较。

这就是你得到语法错误的原因。

一般来说,值得使用“bash -x 脚本”进行调试。

在此脚本中,您可以检测用户是否在第一步中登录。


推荐阅读