我之前的问题,使用 cron 任务清理邮件文件夹没有得到足够好的答案来帮助我。我将任务范围缩小如下:
我希望将邮件从每个用户.spam/cur
和.spam/new
文件夹中移至垃圾邮件教学文件夹中(通过夜间 cron 作业)。它们将在那里被处理和删除。
mv ~/mail/*/*/.spam/{cur,new}/* ~/mail/.sa-learn
如果文件夹不存在,上面的行会生成错误。例如,
+-- mail
+-- sitename.com
+-- username1
| +-- .spam
| +-- cur
| +-- new
+-- username2 <-- no ".spam" folder.
+-- username3
| +-- .spam
| +-- cur
| +-- new
由于如果用户不存在的话为用户创建文件夹会很有用,所以我正在考虑使用touch
来创建它们(如果它们不存在)。
Q1:以下方法足够稳健吗?
for dir in ~/mail/*/*/; do touch "$dir/.spam"; done
for dir in ~/mail/*/*/.spam/; do touch "$dir/cur"; done
for dir in ~/mail/*/*/.spam/; do touch "$dir/new"; done
问题 2:即使文件夹为空,移动命令现在也能正常运行吗?
mv ~/mail/*/*/.spam/{cur,new}/* ~/mail/.sa-learn
Q3:有更聪明的方法吗?
更新4
#!/bin/bash
# SpamAssassin Learn script.
# With help from Kusalananda's answer
# to https://unix.stackexchange.com/questions/336412/creating-spam-folders-in-each-mail-users-account
#
# Any mail the user drops into their spam folder will be moved to a temp folder,
# fed to SpamAssassin's sa-learn and then deleted.
# The script also creates the .spam folders for each account if they don't already exist.
# Run daily as a cron task.
myDomain=sitename.com
# Create .spam/, .spam/cur/ and .spam/new/ folders for each user.
#mkdir -p "$HOME"/mail/"$myDomain"/*/.spam/{cur,new}
for userdir in "$HOME"/mail/"$myDomain"/*; do test -d "$userdir" && mkdir -p "$userdir"/.spam/cur; done
for userdir in "$HOME"/mail/"$myDomain"/*; do test -d "$userdir" && mkdir -p "$userdir"/.spam/new; done
# Create a temp folder.
mkdir -p "$HOME"/mail/.sa-learn/
# Find all the .spam emails and move them to the temp folder.
# IMAP users should see their spam folder empty.
find "$HOME"/mail/"$myDomain" -type f -path "*/.spam/cur/*" -print0 | xargs -0 -I XX mv "XX" "$HOME"/mail/.sa-learn/
find "$HOME"/mail/"$myDomain" -type f -path "*/.spam/new/*" -print0 | xargs -0 -I XX mv "XX" "$HOME"/mail/.sa-learn/
# Feed the emails into the SpamAssassin spam learner.
sa-learn -p ~/.spamassassin/user_prefs --spam "$HOME"/mail/.sa-learn
# Remove the temporary folder and its contents.
rm -rf "$HOME"/mail/.sa-learn
这有效。我似乎在使用 {cur,new} 语法时遇到问题。
用户现在将垃圾邮件放入 .spam 文件夹中。 Cron 作业将它们移动到 .sa-learn 文件夹,将它们提供给 sa-learn,然后删除该文件夹。
答案1
您不能使用 来创建目录touch
,mkdir
为此使用:
mkdir -p "$HOME"/mail/.sa-learn/{cur,new,tmp}
该-p
标志指示mkdir
创建所有中间文件夹(如果它们不存在),并且尝试创建已存在的文件夹不会出错。
这是假设一个外壳可以进行支撑扩展。如果没有,请将其分解为三个单独的mkdir
调用。
移动邮件时(未经测试):
find "$HOME"/mail -type f -path "*/.spam/*" -print0 |
xargs -0 -I XX mv "XX" "$HOME"/mail/.sa-learn/new/
这将找到.spam
下面任何文件夹中的所有邮件(新的或旧的)$HOME/mail
并将它们移动到该.sa-learn/new
文件夹中。
我使用"$HOME"
而不是~
在脚本中使用,因为我认为它看起来更好,它是自记录的,并且它的行为与任何其他变量一样(~
没有)。