Getting the previous month as input for the script

Hi Experts ,

I have scheduled a script "createstructure "in crontab. The script runs every month on 25th .
I am trying to pass the input to the script as the <year><previousmonth>.For example ,if it is running in the month of March 2014 ,the input should be "201402" (2014-year 02-previous month ).For Jan 2015 , the input should be 201412.

 ./createstructure 201402 -->if running in the month of march.

Running Red Hat Enterprise in the server.

Is it doable ?

Thanks

dt=$(echo "$(date --date="1 month ago" +%Y%m)")
./createstructure $(echo $dt)
1 Like

Great..Thanks a lot in2nix4life..

It would be helpful for me if you could just split and explain the command.

Thanks again..:slight_smile:

That's an awful lot of useless echoes... You can boil this whole thing down to

./createstructure "$(date --date="1 month ago" +%Y%m)"

dt=$(date --date="1 month ago" +%Y%m) is sufficient

       -d, --date=STRING
              display time described by STRING, not `now'

So, 1 month ago tells date command to fetch the date that is 1 month ago in the format %Y%m (%Y --> 2014; %m --> 02)

Also, you could say "-1 month" -> minus has the same effect as ago

But on executing this "$(date --date="1 month ago" +%Y%m)" it is giving

$ "$(date --date="1 month ago" +%Y%m)"
-bash: 201402: command not found

In KSH93:

#!/bin/ksh93

LM=$( printf "%(%Y%m)T" "last month" )

./createstructure "$LM"

Thanks a lot balajesuri and Corana688..:slight_smile:

Owe you guys a lot.