views:

200

answers:

6

Hi, I need to create a bash shell script starting with a day and then loop through each subsequent day formatting that output as %Y_%m_d

I figure I can submit a start day and then another param for the number of days.

My issue/question is how to set a DATE (that is not now) and then add a day.

so my input would be 2010_04_01 6

my output would be

2010_04_01
2010_04_02
2010_04_03
2010_04_04
2010_04_05
2010_04_06

Thanks

+2  A: 
#!/bin/bash
inputdate="${1//_/-}"  # change underscores into dashes
for ((i=0; i<$2; i++))
do
    date -d "$inputdate + $i day" "+%Y_%m_%d"
done
Dennis Williamson
A: 

You can pass a date via command line option -d to GNU date handling multiple input formats:

http://www.gnu.org/software/coreutils/manual/coreutils.html#Date-input-formats

Pass starting date as command line argument or use current date:

underscore_date=${1:-$(date +%y_%m_%d)}
date=${underscore_date//_/-}

for days in $(seq 0 6);do 
    date -d "$date + $days days" +%Y_%m_%d;
done
Jürgen Hötzel
+1  A: 
[radical@home ~]$ cat a.sh 
#!/bin/bash

START=`echo $1 | tr -d _`;

for (( c=0; c<$2; c++ ))
do
    echo -n "`date --date="$START +$c day" +%Y_%m_%d` ";
done

Now if you call this script with your params it will return what you wanted:

[radical@home ~]$ ./a.sh 2010_04_01 6
2010_04_01 2010_04_02 2010_04_03 2010_04_04 2010_04_05 2010_04_06
eRadical
A: 

you can use gawk

#!/bin/bash

DATE=$1
num=$2
awk -vd="$DATE" -vn="$num" 'BEGIN{
   m=split(d,D,"_")
   t=mktime(D[1]" "D[2]" "D[3]" 00 00 00")
   print d
   for(i=1;i<=n;i++){
      t+=86400
      print strftime("%Y_%m_%d",t)
   }
}'

output

$ ./shell.sh 2010_04_01 6
2010_04_01
2010_04_02
2010_04_03
2010_04_04
2010_04_05
2010_04_06
2010_04_07
ghostdog74
A: 

Very basic bash script should be able to do this.

Script:
#!/bin/bash

start_date=20100501
num_days=5
for i in seq 1 $num_days
do
    date=date +%Y/%m/%d -d "${start_date}-${i} days"
    echo $date # Use this however you want!
done

Output:
2010/04/30
2010/04/29
2010/04/28
2010/04/27
2010/04/26

anonymous
In the above script, start the sequence from '0' in your case instead of '1'.
anonymous
Also note that the tildes "`" went missing (from the shaded portions) due to the html formating.
anonymous
A: 

Very basic bash script should be able to do this.

#!/bin/bash
start_date=20100501
num_days=5
for i in `seq 1 $num_days`
do
    date=`date +%Y/%m/%d -d "${start_date}-${i} days"`
    echo $date # Use this however you want!
done

Output:
2010/04/30
2010/04/29
2010/04/28
2010/04/27
2010/04/26

anonymous