gpt4 book ai didi

linux - 我有一个用于登录时间的工作脚本,但如果用户未登录,我会收到错误消息

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:12 24 4
gpt4 key购买 nike

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

我正在想办法在用户不在线时跳过这些行

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 脚本”进行调试是值得的。

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

关于linux - 我有一个用于登录时间的工作脚本,但如果用户未登录,我会收到错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55754946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com