Bash date usage for naming
wordpress meta
title: 'Bash Date Usage For Naming'
date: '2018-07-20T10:47:45-05:00'
status: publish
permalink: /bash-date-usage-for-naming
author: admin
excerpt: ''
type: post
id: 1231
category:
- Backups
- Bash
tag: []
post_format: []
title: 'Bash Date Usage For Naming'
date: '2018-07-20T10:47:45-05:00'
status: publish
permalink: /bash-date-usage-for-naming
author: admin
excerpt: ''
type: post
id: 1231
category:
- Backups
- Bash
tag: []
post_format: []
I am recording some scripting I used to create backup classification/retention naming. It can be simplified into one function easily but I kept it like this so I can copy and paste easier which function I need. Script is pretty self explanatory but basically it takes today's date and name my eventual backup file name based on some logic.
# cat test_class.sh
HOSTNAME=$(hostname -s)
BACKUP_CLASSIFICATION="UNCLASSIFIED"
function retention_date() {
MM=`date -d ${1} +%m`
DD=`date -d ${1} +%d`
DAY=`date -d ${1} +%u`
if [ $DD == 01 ]
then
if [ $MM == 01 ]
then
BACKUP_CLASSIFICATION="YEARLY"
else
BACKUP_CLASSIFICATION="MONTHLY"
fi
else
if (($DAY == 7)); then
BACKUP_CLASSIFICATION="WEEKLY"
else
BACKUP_CLASSIFICATION="DAILY"
fi
fi
}
function retention_today() {
MM=`date '+%m'`
DD=`date '+%d'`
DAY=`date +%u`
if [ $DD == 01 ]
then
if [ $MM == 01 ]
then
BACKUP_CLASSIFICATION="YEARLY"
else
BACKUP_CLASSIFICATION="MONTHLY"
fi
else
if (($DAY == 7)); then
BACKUP_CLASSIFICATION="WEEKLY"
else
BACKUP_CLASSIFICATION="DAILY"
fi
fi
}
echo "TEST TODAY"
DATE=`date +%Y-%m-%d`
retention_today
echo $HOSTNAME-$BACKUP_CLASSIFICATION-$DATE
echo
echo "TEST SPECIFIC DATES"
testD=(
'2018-01-01'
'2018-02-02'
'2018-03-01'
'2018-02-06'
'2018-07-14'
'2018-07-15'
)
for D in "${testD[@]}"
do
DATE=`date -d ${D} +%Y-%m-%d`
retention_date $D
echo $HOSTNAME-$BACKUP_CLASSIFICATION-$DATE
done
Run and output.
# ./test_class.sh
TEST TODAY
oci04-DAILY-2018-07-20
TEST SPECIFIC DATES
oci04-YEARLY-2018-01-01
oci04-DAILY-2018-02-02
oci04-MONTHLY-2018-03-01
oci04-DAILY-2018-02-06
oci04-DAILY-2018-07-14
oci04-WEEKLY-2018-07-15