How to copy the previous month files using shell script?

could you please assist the below query.

i had written the below piece of code to copy the files from one directory to another. For current month files had been copied ,unfortunately the previous month files not copied.

Please find the below directory structure:-

ls -lrt
total 1824
drwxrwxrwx 2 root root 1839104 Oct 3 17:14 9
drwxrwxrwx 2 root root 20480 Nov 30 02:25 11----Nov month directory structure.
drwxrwxr-x 2 idcuser idcuser 4096 Dec 4 10:28 12---Dec Month directory strucure

using the below srcript, i can copy only the current month files that only four days of files and other files are not copied .Due to other files were in Nov month.


#!/bin/bash

Day=$(date +%A)
dt=$(date +%d)
yr=$(date +%Y)
mon=$(date +%b)
month=$(date +%m)
Date=$(date +%d_%m_%Y)

cd /home/idcuser/venkat/pdf_dir

find . -type f -exec rm -f {} \;

cd /home/skyline4/bills/${yr}/${month}

find . -type f -name "*.pdf" -mtime -7 -exec cp "{}" /home/idcuser/venkat/pdf_dir/ \;



Calculate the previous month in the shell:

# set several shell variable in one stroke
eval $(date '+yr=%Y month=%m')
echo "This month: ${month}:${yr}"
lastmonth=$((month - 1))
if [[ $lastmonth -ge 1 ]]
then
  lastyr=$yr
else
  lastmonth=12
  lastyr=$((yr - 1))
fi
echo "Last month: ${lastmonth}:${lastyr}"

Last but not least, make sure that directories are accessable!

cd /home/idcuser/venkat/pdf_dir || exit
cd /home/skyline4/bills/${lastyr}/${lastmonth} || exit
1 Like

Thanks all, had applied the below logic to get the last month file.

#!/bin/bash

Day=$(date +%A)
dt=$(date +%d)
yr=$(date +%Y)
mon=$(date +%b)
month=$(date +%m)
prev_month=$(date  +%m -d"last month")
Date=$(date +%d_%m_%Y)

cd /home/idcuser/venkat/pdf_dir

find . -type f -exec rm -f {} \;

if [[ "$dt" -lt '7' ]]
then
cd /home/venkat/bills/${yr}/${prev_month}
find . -type f -name "*.pdf" -mtime -7 -exec cp "{}" /home/idcuser/fiberbysky/pdf_dir/ \;
fi

cd /home/venkat/bills/${yr}/${month}

find . -type f -name "*.pdf" -mtime -7 -exec cp "{}" /home/idcuser/venkat/pdf_dir/ \;