Shell Scripting to extract date - shell

Need a logic in shell scripting where I give the start and end date,
say
startDate=20140101 &
endDate=20160130
I should be able to extract startDate_new=20140122 and endDate_new=20140221 in first loop.
In next loop will need startDate_new=20140222 and endDate_new=20140321 so on, till startDate_new=20151221 & endDate_new=20160122 and exit out. Can you provide any shell scripting logic that can be used to achieve this.
test.sh has,
startdate=2013-03-01
enddate=2013-04-30
curr="$startdate"
while true; do
echo "$curr"
[ "$curr" \< "$enddate" ] || break
curr=$( date +%Y-%m-%d --date "$curr +1 day" )
done
the above code prints,
2013-03-01
2013-03-02
2013-03-03
2013-03-04
2013-03-05
2013-03-06
2013-03-07
2013-03-08
.
.
.
.
2013-04-30
Can you help me how to extract the range I mentioned above ?
Came up with a new logic,
startdate=2013-03-21
enddate=2014-05-30
curr="$startdate"
while true; do
[ "$curr" \< "$enddate" ] || { echo "$curr"; break; }
echo "$curr"
curr=$( date +%Y-%m-%d --date "$curr +1 month" )
end=$( date +%Y-%m-%d --date "$curr +1 month +1day" )
done
the above logic gives
2013-03-21
2013-04-21
2013-05-21
2013-06-21
2013-07-21
2013-08-21
2013-09-21
2013-10-21
2013-11-21
2013-12-21
2014-01-21
2014-02-21
2014-03-21
2014-04-21
2014-05-21
2014-06-21
Can you help with how to retrieve end date as 22nd of each month ?

Make a function:
# Usage: drange startdate endate [ time_increment ]
drange ()
{
curr="$( date +%Y-%m-%d --date $1)"
enddate="$( date +%Y-%m-%d --date $2)"
shift 2
inc="${*:-+1 day}"
until [ "$curr" \> "$enddate" ]; do
echo $curr
curr=$( date +%Y-%m-%d --date "$curr $inc" )
done
}
Run it like so:
drange 20140222 20140321
drange 20151221 20160122 +1 month
s=20151221 e=20160122 i="+1 month"
drange $((s + 1)) $e $i

Related

Check for date range with bash scripting

I'm trying to make a script that is working from 12/24/2020 through 06/01/2021. For now I olny have it working only for 2 dates with this:
if [ "$(date +'%m%d')" != "1224" ] && [ "$(date +'%m%d')" != "1226" ];
So this script should be working from 12/24 - 01/06.
Any suggestions? Thanks
You can use the +%s option in date to convert the start/finish dates to epoch time. You supply the dates using the -d option.
Then, you retrieve the current date using +%s again and compare using standard integer comparison, like this:
start=$(date +%s -d '12/24/2020')
finish=$(date +%s -d '06/02/2021')
now=$(date +%s)
if [ $now -ge $start ] && [ $now -lt $finish ]
then
echo "Do something"
else
echo "Skip"
fi
Edit: For the finish date, its necessary to use the day after your intended finishing date and compare using -lt. This is because date will return the timestamp for the start of the specified date. So doing this, you end up having the comparison succeed until midnight on 06/01/2021. Thanks to #gordon-davisson for pointing this out.
beg='20201224'
end='20210601'
now=$(date +'%Y%m%d')
if (( beg <= now )) && (( now <= end)); then

Outputting if the 10 day period is finished

I want to write a bash script that determines the 10 day period (decade) has ended relative to the start date (in the format YYYY-MM-DD).
If the 10 day period is finished script has to output the 10 days period.
Im new in bash and has a lot syntax errors with code, help me pls.
#!/bin/bash
# GNU bash, version 4.3.46
CURRENT_DATE=$(date +%Y-%m-%d)
START_DATE=2019-01-01
IS_TODAY_DECADE_CALCULATION_DAY = (CURRENT_DATE - START_DATE) % 10
if [ $IS_TODAY_DECADE_CALCULATION_DAY -eq 0 ]
then
BEGIN_DATE = $("$CURRENT_DATE - 11 days" +%Y-%m-%d)"
END_DATE = $("$CURRENT_DATE - 1 day" +%Y-%m-%d)"
echo "Period is="$BEGIN_DATE":"$END_DATE"
else
echo "Decade is not finished."
fi
You should compare the unix time stamps. If the time stamp "now+10 days" is larger than the start date, the period is ended.
#! /bin/bash
DATE_OLD=$(date "+%F" -d "-11 days")
DATE_NOW=$(date "+%F")
TEST_DATE_NOW=$(date "+%s" -d ${DATE_NOW})
TEST_DATE_OLD=$(date "+%s" -d ${DATE_OLD})
DIVIDER=$(( (TEST_DATE_NOW - TEST_DATE_OLD) / (60*60*24) ))
REMAINING=$(( DIVIDER % 10 ))
echo "Days between ${DATE_OLD} and ${DATE_NOW} is $DIVIDER"
if [ ${DIVIDER} -gt 0 ]; then
echo "Date ${DATE_OLD} is in the past"
else
echo "Date ${DATE_OLD} is in the future"
fi
if [ $REMAINING -eq 0 ]; then
echo "Ten days period ended"
else
echo "Still in ten day period"
fi
exit 0;
The question implies that the code should identify each 10 day period starting on a specific START_DATE. Bash does not have date math - it can not calculate difference between dates (as expected by '(CURRENT_DATE - START_DATE)'). Two options
Convert date to seconds since Unix Epoch, and do the math on those values, OR
Use date utilities package, OR
using Python, awk, perl
Implementing #1 is simple. Notice few changes to assignments - in particular no spaces are allowed in assignments variable=expression, or let variable=expression
#! /bin/bash
CURRENT_DATE=$(date +%Y-%m-%d)
START_DATE=2019-01-01
# Instead of IS_TODAY_DECADE_CALCULATION_DAY = (CURRENT_DATE - START_DATE) % 10
SEC_IN_DAY=$((60*60*24))
let D1=$(date '+%s' -d "$CURRENT_DATE Z")/SEC_IN_DAY
let D2=$(date '+%s' -d "$START_DATE Z")/SEC_IN_DAY
let IS_TODAY_DECADE_CALCULATION_DAY=(CURRENT_DATE-START_DATE)%10
# Rest of script here
if [ $IS_TODAY_DECADE_CALCULATION_DAY -eq 0 ]
then
BEGIN_DATE=$(date -d "$CURRENT_DATE - 11 days" +%Y-%m-%d)
END_DATE=$(date -d "$CURRENT_DATE - 1 day" +%Y-%m-%d)
echo "Period is=$BEGIN_DATE:$END_DATE"
else
echo "Decade is not finished."
fi

Format date variable in shell script

I'm trying to the month number of the last Monday of this week. I got it to check what day of the week it is and if it's not Monday then subtract x days and set that new date as the variable value.
What I'm having trouble with is formatting this variable to only get the month. Everything works except the 2nd to last line below.
startDate=$(date)
weekDayNum=$(date +'%u') # 1 is Monday
# If today is NOT Monday
if [ weekDayNum > 1 ];
then
# Get the date for the last Monday
newWeekDayNum=$(($weekDayNum-1))
startDate=$(date -j -v-${newWeekDayNum}d)
fi
month=$(date -d "$startDate" +'%m')
echo $month```
[ weekDayNum > 1 ] doesn't test for numeric order. Use [ $weekDayNum -gt 10 ] (you also did not access the value of your weekDayNum variable).
It seems you have to supply the format string in the BSD variant of date:
This works for me:
#!/usr/bin/env bash
LANG=C
startDate=$(date)
weekDayNum=$(date +'%u') # 1 is Monday
# If today is NOT Monday
if [ $weekDayNum -gt 1 ];
then
startDate=$(date -j -v "-$(($weekDayNum - 1))d")
fi
month=$(date -j -f "%a %b %d %T %Z %Y" "${startDate}" +'%m')
echo $month
Use expr to convert it to number.
month=$(date -d "$startDate" +'%m')
month=$(expr $month + 0)
echo $month
Output:
8

Iterating over a range of dates in a unix shell script

I am trying to create a script in which 4 days ago date should be equal to to current date if it is not then add 1 more day and check. Below is the one i have created but still not clear about answer.
#!/bin/bash
batchdate=`date --date "4 day ago" '+%Y%m%d'`
matchdate=`date --date "today" '+%Y%m%d'`
for i in {0..4}
do
if [ $batchdate != $matchdate && $NEXT_DATE != $matchdate ]; then
NEXT_DATE=$(date +%Y%m%d -d "$batchdate + $i day")
echo "$NEXT_DATE"
break
fi
done
First, define a little helper function to avoid doing the same thing in slightly different ways:
get_date () {
date +%Y-%m-%d --date "$1"
}
Now, you have two variables: the current date, which will never change, and the starting date, which you will increment one day at a time until it matches the current date.
then=$(get_date "4 days ago")
now=$(get_date "today")
while [[ $then != $now ]]; do
then=$(get_date "$then + 1 day")
echo "$then"
done

Generate a date+hour sequence with a given date

Given a date in format 20130522, I need to generate a sequence of date+hour as below:
2013052112,2013052113,2013052114,...,2013052122,2013052123,
2013052200,2013052201,2013052202,...,2013052222,2013052223,
2013052300
in which the first date+hour is 12 hours before the given date and the last date+hour is the midnight in the next day of the given date.
I tried several ways but none of them is ideal. How to generate such a sequence in a clean way using shell script? Thanks!
--Edit--
Per your request, this is what I have so far:
day=20130522
begin=`date --date "$day -12 hours"`
begin=`date -d "${begin:0:8} ${begin:8:2}" +%s`
end=`date --date "$day +1 day"`
end=`date -d "${end:0:8} ${end:8:2}" +%s`
datestr=`date -d #${begin} +%Y%m%d%H`
let begin=$begin+3600
while [ $begin -le $end ]
do
hr=`date -d #${begin} +%Y%m%d%H`
datestr="$datestr,$hr"
let begin=$begin+3600
done
and this is what I got from above:
2013052100,2013052101,2013052102,...,2013052123,
2013052200,2013052201,2013052202,...,2013052223,
2013052300
You can use date and brace expansion:
date=20130522
echo $(date -d "-1 day $date" +%Y%m%d){12..23} \
"$date"{00..23} \
$(date -d "+1 day $date" +%Y%m%d)00
Output (wrapped):
2013052112 2013052113 2013052114 2013052115 2013052116 2013052117 2013052118 2013052119 2013052120
2013052121 2013052122 2013052123 2013052200 2013052201 2013052202 2013052203 2013052204 2013052205
2013052206 2013052207 2013052208 2013052209 2013052210 2013052211 2013052212 2013052213 2013052214
2013052215 2013052216 2013052217 2013052218 2013052219 2013052220 2013052221 2013052222 2013052223
2013052300
Your code was quite well. What I think is that you used so much bash conversion, while date is very powerful and handles in an easier way.
I rewrited something and now I get this:
day=20130522
begin=$(date --date "$day -12 hours" "+%s")
end=$(date --date "$day +1 day" "+%s")
hr=$(date --date "#$begin" "+%s")
while [[ $hr -lt $end ]]
do
hr=$(($hr + 3600))
echo $(date -d "#$hr" "+%Y%m%d %H")
done
$ ./script
20130521 13
20130521 14
.../...
20130522 22
20130522 23
20130523 00

Resources