有人可以告诉我创建 shell 脚本以每 20 天向我发送一次邮件的逻辑或整个脚本吗
答案1
如果只是一封带有文本的邮件,没有附件:
/一些/路径/script.sh
内容:
#send me an email:
cat text | mail -s "subject" [email protected]
要每 20 天获取一次,一种方法可能是更改脚本以添加:
#send me an email:
cat text | mail -s "subject" [email protected]
#and the script itself re-schedule itself to start again in 20 days:
echo "$0" | at now + 20 days #And remember to launch that script using its full path
另一种方法是使用 crontabs(crontab -e
作为您希望运行脚本的用户)。要通过 crontab 每 20 天运行一次脚本,我让你man crontab
^^
如果您需要该邮件中的附件,最好安装“mutt”(或易于在命令行中使用的类似程序,并且能够处理附件)。
===
现在您明确表示想要使用每日 cron 的另一种方法是:您每天运行一个脚本,并希望它在 20 天后执行一些特殊操作(即发送电子邮件)?
一种方法是将这部分放在该脚本中:
#the script
#near the beginning:
[ ! -e /some/flagfile ] && touch /some/flagfile #create /some/flagfile, ONCE.
... #the usual script treatment, if any
#and the test: if our flagfile is >=20 days old, we mail a msg and delete the flag
sleep 10 #IMPORTANT: that way we are sure the flag done 20 days ago is at least
# 20days+a few seconds, and thus the following test will work !
if ( find /some -mtime +20 -print | grep '/some/flagfile$' >/dev/null )
then
# we found a /some/flagfile of at least 20 days!
cat /some/message | mail -s "subject" [email protected]
rm /some/flagfile #you could add checks that the email worked...
# so next time you run the script, it will create the new /some/flagfile.
# But if you prefer to have the 20 days start "now" instead of when the script
# is run next, you could uncomment the next line instead:
#touch /some/flagfile
fi
...
答案2
如果您运行此程序的计算机从未关闭过,您可以启动一个像这样的小脚本:
while :; do sleep 20d; echo "hello Bob" | mail -s "subject" [email protected]; done
上面的脚本将永远运行(while :;
),它将等待 20 天(睡眠 20 天),然后向您发送邮件,然后再等待 20 天,再次向您发送邮件,依此类推。
另一种虽然丑陋但应该可行的方法是手动生成 cron 行,然后将它们添加到您的 crontab 中:
DATE=$(date -d "$(date -d @"$(($(date +%s) + 1728000))")")
for i in {1..16}; do
DATE=$(date -d "$(date -d @"$(( $(date -d "$DATE" +%s) + 1728000))")" +"%e %b");
echo "0 0 $DATE echo \"hello bob\" | mail [email protected]"
done
运行上面的脚本会产生以下输出:
0 0 8 Dec echo "hello bob" | mail [email protected]
0 0 28 Dec echo "hello bob" | mail [email protected]
0 0 17 Jan echo "hello bob" | mail [email protected]
0 0 6 Feb echo "hello bob" | mail [email protected]
0 0 26 Feb echo "hello bob" | mail [email protected]
0 0 18 Mar echo "hello bob" | mail [email protected]
0 0 7 Apr echo "hello bob" | mail [email protected]
0 0 27 Apr echo "hello bob" | mail [email protected]
0 0 17 May echo "hello bob" | mail [email protected]
0 0 6 Jun echo "hello bob" | mail [email protected]
0 0 26 Jun echo "hello bob" | mail [email protected]
0 0 16 Jul echo "hello bob" | mail [email protected]
0 0 5 Aug echo "hello bob" | mail [email protected]
0 0 25 Aug echo "hello bob" | mail [email protected]
0 0 14 Sep echo "hello bob" | mail [email protected]
0 0 4 Oct echo "hello bob" | mail [email protected]
将这些行添加到您的 crontab 将导致明年每 20 天向您发送一封电子邮件。明年你必须再次运行它。