linux - 我有一个登录时间的工作脚本,但如果用户未登录,我会收到错误消息
问题描述
我有一个工作脚本,它告诉用户登录了多长时间。但是如果用户没有登录,它会说他们已注销,但它会给我一个脚本中间的测试错误。
我试图弄清楚如果用户不在线如何跳过这些行
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
解决方案
如果用户未登录,则无法获得“who | grep $1 | cut -c 37,38”的任何输出。因此,您不能将空字符串与整数进行比较。
这就是你得到语法错误的原因。
一般来说,值得使用“bash -x 脚本”进行调试。
在此脚本中,您可以检测用户是否在第一步中登录。
推荐阅读
- android - PlayGames ERROR_INVALID_CREDENTIAL
- java - 我们可以在 python 代码之上引入一些 java 或任何其他语言包装器,以隐藏/加密我们的 python 代码以防止重新设计吗?
- html - Div 中的居中按钮,位于其他居中文本下方
- python - Python字典中基于默认参数的映射命令
- python - 没有 URL 列表的多线程请求
- python - 删除列表中连续整数的最快和更有效的方法是什么?
- clojure - 克洛朱尔。为什么需要包装惰性序列?
- c - 101到201的奇数之和
- django - 浏览器向 django 发出 CORS 请求的 OPTIONS 请求,但没有 POST
- entity-framework - 使用 Azure 托管标识运行 EF Code First 迁移时如何修复“CREATE SCHEMA”失败错误