Bash脚本:根据没有年份的日期检查今天的日期

时间:2013-05-22 23:35:26

标签: bash

我想在到期日前四周发送续订提醒电子邮件。我将所有细节存储在一个数组中,但我无法弄清楚如何检查今天的日期是否在数组中的日期之前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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

您可以在check日期之前的28天获取月份和日期,如下所示:

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

更新

仅在当前日期是check日期之前的第28天提醒您,您可以使用相同的月份日期格式获取每个日期并比较字符串相等性:

# ...
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