簡體   English   中英

Bash腳本:對照沒有日期的日期檢查今天的日期

[英]Bash script: Checking today's date against a date without year

我想在到期日前四周發送續訂提醒電子郵件。 我將所有詳細信息存儲在數組中,但是我不知道如何檢查今天的日期是否早於數組中日期的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

最好使用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

您可以這樣獲得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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM