karthikraj karthikraj - 4 months ago 8
Bash Question

Compress and moving the files to respective directory

Please help on this,

I have the folder which has logs on daily basis,so my target is to tar and zip the file and move to the separate directory on very next day using cron.

***All the logs are saved in the format as "server.log.2016-08-08" (server.log.year-month-date)

inorder to find the file i used

for i in


find . -type f -name server.log.$(date "+%Y-%m-%d" -d '1 day ago')


if the day is 2016-08-09 , it will find the yesterday server log (server.log.2016-08-07)

***then in order to compress it i used
do tar -czvf server.log.$(date "+%B-%m-%d" -d '1 day ago').tar.gz $i --remove-files


****I have folders as January,February....December in the path /opt/Solartis_Monitoring/logsbackup/(jan,feb...dec)

****now i need to move the archived and compressed file to backup location
if the compressed logs belongs to the month of august then it should be in August folder same case applicable to all the months.

so i used
mv server.log.$(date "+%B-%m-%d" -d '1 day ago').tar.gz /opt/Solartis_Monitoring/logsbackup/$(date "+%B")


I am using crontab for this to be executed.

Problem:



The problem is if the file is executing on 1 st day of next month (september) ,script will find the aug 31 file and it will compress but while moving the compressed file ,it will be moved to september month rit??
since i am using
/opt/Solartis_Monitoring/logsbackup/$(date "+%B")


here
date "+%B"
will be expanded as September and my file will be moved to /opt/Solartis_Monitoring/logsbackup/september right....

How to solve this..august file is suppose to moved in the folder of august

Script :



cd /opt/Solartis_Monitoring/JON_Server/logs

for i in `find . -type f -name server.log.$(date "+%Y-%m-%d" -d '1 day ago')`
do tar -czvf server.log.$(date "+%B-%m-%d" -d '1 day ago').tar.gz $i --remove-files

mv server.log.$(date "+%B-%m-%d" -d '1 day ago').tar.gz /opt/Solartis_Monitoring/logsbackup/$(date "+%B")
done

UUU UUU
Answer

Try This.

date "+%B" -d '1 day ago' 

Above command will give you the Month parameter of yesterday.

cd /opt/Solartis_Monitoring/JON_Server/logs 
for i in `find . -type f -name server.log.$(date "+%Y-%m-%d" -d '1 day ago')`
do tar -czvf server.log.$(date "+%B-%m-%d" -d '1 day ago').tar.gz $i --remove-files
mv server.log.$(date "+%B-%m-%d" -d '1 day ago').tar.gz 
/opt/Solartis_Monitoring/logsbackup/$(date "+%B" -d '1 day ago')