Reputation: 1435
I have a Bash script that takes an argument of a date formatted as yyyy-mm-dd.
I convert it to seconds with
startdate="$(date -d"$1" +%s)";
What I need to do is iterate eight times, each time incrementing the epoch date by one day and then displaying it in the format mm-dd-yyyy.
Upvotes: 56
Views: 130388
Reputation: 185025
date -d
is not portable across OSes, and sometimes not reliable at all.
With Perl with core modules (installed by default), this is a robust, portable and reliable way in a shell:
perl -MTime::Piece -MTime::Seconds -sE '
my $d = Time::Piece->strptime($mydate, "%Y-%m-%d %H:%M:%S");
($dow, $month, $dom, $hour, $year) = split / +/, $d +ONE_DAY;
my $dateold = Time::Piece->strptime(
"$dow $month $dom $year $hour",
"%a %b %d %Y %H:%M:%S");
say $dateold->strftime("%Y-%d-%m %H:%M:%S");
' -- -mydate='2023-06-03 06:21:33'
2023-07-03 06:21:33
Upvotes: 1
Reputation: 3051
Use the date
command's ability to add days to existing dates.
The following:
DATE=2013-05-25
for i in {0..8}
do
NEXT_DATE=$(date +%m-%d-%Y -d "$DATE + $i day")
echo "$NEXT_DATE"
done
produces:
05-25-2013
05-26-2013
05-27-2013
05-28-2013
05-29-2013
05-30-2013
05-31-2013
06-01-2013
06-02-2013
Note, this works well in your case but other date formats such as yyyymmdd may need to include "UTC" in the date string (e.g., date -ud "20130515 UTC + 1 day"
).
Upvotes: 125
Reputation: 1442
There is another way similar to this, may not be as fast as adding 86400 seconds to the day, but worth try -
day="2018-07-01"
last_day="2019-09-18"
while [[ $(date +%s -d "$day") -le $(date +%s -d "${last_day}") ]];do
echo $i;
# here you can use the section you want to use
day=$(date -d "$day next day" +%Y-%m-%d);
done
Upvotes: 2
Reputation: 21
Increment date in bash script and create folder structure based on Year, Month and Date to organize the large number of files from a command line output.
for m in {0..100}
do
folderdt=$(date -d "Aug 1 2014 + $m days" +'%Y/%m/%d')
procdate=$(date -d "Aug 1 2014 + $m days" +'%Y.%m.%d')
echo $folderdt
mkdir -p $folderdt
#chown <user>:<group> $folderdt -R
cd $folderdt
#commandline --process-date $procdate
cd -
done
Upvotes: 2
Reputation: 173
Just another way to increment or decrement days from today that's a bit more compact:
$ date %y%m%d ## show the current date
$ 20150109
$ ## add a day:
$ echo $(date %y%m%d -d "$(date) + 1 day")
$ 20150110
$ ## Subtract a day:
$ echo $(date %y%m%d -d "$(date) - 1 day")
$ 20150108
$
Upvotes: 2
Reputation: 10653
startdate=$(date -d"$1" +%s)
next=86400 # 86400 is one day
for (( i=startdate; i < startdate + 8*next; i+=next )); do
date -d"@$i" +%d-%m-%Y
done
Upvotes: 7