1

我想在到期日前四个星期发送续订提醒电子邮件。我将所有详细信息存储在一个数组中,但我不知道如何检查今天的日期是否比数组中的日期早 28 天。

这是我到目前为止所得到的,任何有关如何进行日期检查的帮助将不胜感激:

#!/bin/sh

adminemail="me@gmail.com"

account[1]="June 03|john@gmail.com|John"
account[2]="April 17|jane@gmail.com|Jane"
account[3]="November 29|sarah@gmail.com|Sarah"

for check in "${account[@]}"
do
    renew=$(echo $check | cut -f1 -d\|)
    email=$(echo $check | cut -f2 -d\|)
    name=$(echo $check | cut -f3 -d\|)

    # check date is 28 days away
    if [ ?????? ]
    then
        subject="Your account is due for renewal"
        text="
Dear $name,

Your account is due for renewal by $renew. blah blah blah"

        echo "$text" | mail -s "$subject" $email -- -r $adminemail
    fi
done
4

2 回答 2

4

您可以像这样获取日期前 28 天的月份和日期check

warning_date=$(date --date='June 03 -28 days' +%s)

相同格式的当前日期:

current_date=$(date +%s)

由于它们都是数字且具有相同的比例(自纪元以来的秒数),现在您可以检查是否$current_date大于$warning_date

if [ $warning_date -lt $current_date ]; then
  # ...
fi

现在把它们放在一起:

# ...
current_date=$(date +%s)

for check in ${account[@]}; do
  # ...
  renew=$(echo $check | cut -f1 -d\|)

  # 28 days before the account renewal date
  warning_date=$(date --date="$renew -28 days" +%m%d)

  if [ $warning_date -lt $current_date ]; then
    # Set up your email and send it.
  fi
done

更新

仅当当前日期是该日期之前的第 28 天时才需要提醒check您,您可以获得相同月份日期格式的每个日期并比较字符串是否相等:

# ...
current_date=$(date "+%B %d")

for check in ${account[@]}; do
  # ...
  renew=$(echo $check | cut -f1 -d\|)

  # The 28th day before the account renewal day
  warning_date=$(date --date="$renew -28 days" "%B %d")

  if [ $warning_date == $current_date ]; then
    # Set up your email and send it.
  fi
done
于 2013-05-23T00:09:49.537 回答
3

最好使用 Unix 时间戳进行日期比较,因为它们是简单的整数。

#!/bin/bash

adminemail="me@gmail.com"

account[1]="June 03|john@gmail.com|John"
account[2]="April 17|jane@gmail.com|Jane"
account[3]="November 29|sarah@gmail.com|Sarah"

for check in "${account[@]}"
do
    IFS="|" read renew email name <<< "$check"

    # GNU date assumed. Similar commands are available for BSD date
    ts=$( date +%s --date "$renew" )
    now=$( date +%s )
    (( ts < now )) && (( ts+=365*24*3600 )) # Check the upcoming date, not the previous

    TMINUS_28_days=$(( ts - 28*24*3600 ))
    TMINUS_29_days=$(( ts - 29*24*3600 ))
    if (( TMINUS_29_days < now && now <  TMINUS_28_days)); then        
        subject="Your account is due for renewal"
        mail -s "$subject" "$email" -- -r "$adminemail" <<EOF
Dear $name,

Your account is due for renewal by $renew. blah blah blah
EOF    
    fi
done
于 2013-05-22T23:56:53.033 回答