这是我的帖子的续篇这里
虽然 AB 为我提供了正确的答案,即利用 的输出last
并检查它是否是当前登录,但它并没有解决我的问题。我在登录时检查了 的输出last
,发现它没有显示该月首次登录的底线。相反,首次登录位于顶部(7 月份登录的上方)。
我没有保存屏幕截图,因为截至目前,last
的输出已删除了 7 月份的所有屏幕截图。它似乎/var/log/wtmp
没有像我预期的那样在登录时立即刷新。我帖子第 1 部分中的一些评论建议它在每个月的第一天刷新。无论如何,我只想在启动时运行一些脚本,告诉我我当前的登录是否是该月的第一次登录。
这是我编写的一个简单脚本:
firstLogin=$(last | tail -3 | head -1)
# check if "still logged in" (this is current log in)
if [[ $(grep "still" <<< $firstLogin) ]]; then
notify-send "first login!!!!"
fi
有人能建议一种方法吗?我将不胜感激任何帮助。
编辑:正如您可能在示例脚本中看到的,我尝试在没有任何临时文件帮助的情况下完成此操作。但是,如果没有其他方法可以在没有临时文件的情况下完成此操作,我可能会继续使用它。
答案1
为什么不让自己的生活变得更简单,每次登录时在文件中记录当前月份并测试其先前的值呢?
当您登录并且您的 shell 是 bash 时,它将读取文件
~/.bash_profile
、、~/.bash_login
和~/.profile
。
例如,在以下任意一行中添加:
now=$(date +%m)
last=$(<~/.mylastlogin)
if [ $now != "$last" ]
then notify-send "first login!!!!"
echo $now >~/.mylastlogin
fi
unset now last
为了避免使用临时文件,您可以使用任何现有文件,例如 ~/.profile 文件本身。touch
每次登录后比较其ls -l
时间输出即可。例如:
now=$(date +%m)
last=$(ls -ld --time-style=+%m ~/.profile | awk '{print $6}')
if [ $now != "$last" ]
then notify-send "first login!!!!"
touch ~/.profile
fi
unset now last
答案2
仅查询用户当前月份的登录情况并进行计数。
如果多于一个,则表示您本月已经登录。
在终端中复制/粘贴的一行代码:
[ $(last -R "$USER" | grep -c $(LC_ALL=en_US.utf8 date +%b)) -gt 1 ] && echo 'nope' || echo 'first login'
使用以下命令输出进行测试last
:
root pts/1 Tue Feb 18 13:38 still logged in
root pts/1 Tue Feb 18 13:17 - 13:38 (00:20)
root pts/0 Tue Feb 18 07:27 still logged in
root pts/1 Mon Feb 17 09:29 - 17:08 (07:39)
root pts/0 Fri Jan 31 09:50 - 13:54 (04:03)
root pts/1 Tue Jan 28 09:19 - 17:11 (07:52)
root pts/0 Mon Jan 27 13:58 - 18:01 (3+04:02)
root pts/0 Wed Dec 18 11:54 - 12:18 (00:24)
root pts/0 Tue Dec 17 17:24 - 19:27 (02:02)
root pts/1 Tue Dec 17 16:30 - 16:44 (00:13)
或者,修改示例脚本:
countLogin=$(last -R "$USER" | grep -c $(LC_ALL=en_US.utf8 date +%b))
# check if equals 1
if [ "$countLogin" -eq 1 ] ; then
notify-send "first login!!!!"
fi