I have a file named "GI_GR.csv" generated by SAP everyday. What I need is every last date of the month ( Jan 31, Feb 28/29, Mar 31, etc), the file is copied to subfolder named "archive" and rename it to "GI_GR_Jan.csv" for January and so on. What I want to ask is, how to check if it's the end of the month and rename the file adding month's name?
Please remember to post what Operating System and version you have and what Shell you use.
One pretty portable way of finding the last day of the month:
last_day=$(cal | tr ' ' '\n'|grep -v '^$' |tail -1)
date_day=$(date +%d)
if [ $date_day -eq $last_day ]
then
## copy process
## rename process
fi
@kris.adrianto
I notice that @jamie123 has interpreted the post as meaning that you want to delete the original file. Do you?
Similarly @jamie123 has sort of made a point by using the full date. If the process is to run for more than a year, you will need Month and Year in the filename.
There is no way to schedule a cron for the last day of the month unless you put the date in manually. It is easier to schedule a cron to run a script daily and to detect whether it is the last day of the month in the script.
The method above using cal depends on the default behaviour of cal (as poster mentioned). Run cal without any arguments and ensure it shows only one month, then the method will work.
On some systems cal without arguments would show previous, current and next month, in that case the method can be augmented with running cal with current month as an argument:
@jamie_123
thanks for the answer, but I don't need to rename the file everyday, just at the end of the month.
@methyl
I'm using Solaris 5.10 and bourne shell.
I just want to copy the file not to move it. Yes, I also need year in my filename, but I have no problem in changing the filename. I agree with you, it is easier to run the script daily and checking whether if its the last day of the month. But I still don't understand about the first line of the code you made, could you explain more about this line:
when I wrote codes above directly (not in script), there is an error after I entered the code, it says that syntax error: `last_days=$' unexpected. What is the correct syntax to assigning variable in bourne shell?
All modern unix and Linux systems come with something better than the old Bourne Shell.
Solaris is unusual in that /usr/bin/sh is the old Bourne Shell. The $( ) syntax is valid in Korn Shell (/usr/bin/ksh) and the Posix Shell (/usr/xpg4/bin/sh).
Though I have never seen a version of cal where the default output is two months, the syntax for the current month would be: