如果有类似的邮件,我该如何检查bash
或python
(首选)?unread
/var/spool/mail/$USER
pam_mail
我想用它来定制我自己的莫德脚本,motd.dynamic
答案1
传统上判断邮箱文件中是否有未读邮件的方法是检查访问时间是否早于修改时间。
您可以使用以下命令轻松找到这些时间stat
;通过指定自定义输出格式,可以将这些值导入到 shell 中:
eval $(stat -c 'atime=%X; mtime=%Y' /var/spool/mail/$USER)
之后您可以比较这些值:
if [ $atime -le $mtime ]; then echo 'You have new mail'; fi
为了使其更加健壮,请首先检查邮件文件是否存在。
答案2
我采纳了 @wurtel 给我的想法并将其变成了 python:
def mail():
# See https://tools.ietf.org/html/rfc4155
import os
import os.path
import time
mailbox = '/var/spool/mail/' + curr_user()
def d( content, color = COLOR_NORMAL ):
return colored( justify( content, 1 ) + '\n', color )
def none():
return d( 'No new mail' ) if MAIL_NONE_DISPLAY else ''
if not os.path.isfile( mailbox ): return none()
stat = os.stat( mailbox )
if stat.st_mtime > stat.st_atime:
# mailbox has been modified after accessed.
if MAIL_NEW_COUNT:
# check how many new mails.
count = 0
newlines = 2
for l in open( mailbox ):
if l.isspace(): newlines += 1
else:
# New == We have a From header the date > atime.
if newlines == 2 and l.startswith( 'From ' ) and time.mktime( time.strptime( l.split( None, 2 )[2].strip() ) ):
count += 1
newlines = 0
# open() will change access time, correct it.
os.utime( mailbox, (time.time(), stat.st_mtime) if MAIL_CONSIDER_READ else (stat.st_atime, stat.st_mtime) )
return d( 'You have {0} new mails'.format( count ), COLOR_WARN ) if count else none()
else: return d( 'You have new mail', COLOR_WARN )
else: return none()