I have a file CBD_DATA.zip
present in a directory: /home/cbd_dev/CBD_DATA.zip
. I want to move it to the directory /home/sundaram_srivastava/archives/
as CBD_DATA_{DateTimeStamp}.zip
.
I have tried using a cron job:
* * * * * mv /home/cbd_dev/CBD_DATA.zip /home/sundaram_srivastava/archives > /home/sundaram_srivastava/archives/CBD_DATA_`date +\%d\%m\%y`.zip
The problem with the cron job above is that it moves the file as CBD_DATA.zip
into another directory with the same name and then it creates another file CBD_DATA_110620
.
Now, the file CBD_DATA_110620
is 0 KB. So, in the destination directory, I have two files, CBD_DATA.zip
and CBD_DATA_110620
, but I want just one and it should not be empty.
What should I change in my cron code?
First, I'd try and figure out the command on its own, without a cron job. What you're doing is something like this (with shortened directory paths for readability):
mv /foo/CBD_DATA.zip /foo/archives > /foo/archives/CBD_DATA_`date +%d%m%y`.zip
This moves the file and then creates a new empty file; there is no output from the mv
command, and the redirection has nothing to redirect, so the file with the datestamp is empty.
The second argument for the mv
command is the new location itself; if it is a directory, the filename stays the same, but if it is not a directory, it is interpreted as the new name. You don't need any redirection.
mv /foo/CBD_DATA.zip "/foo/archives/CBD_DATA_$(date '+%d%m%y').zip"
I have replaced the deprecated backticks in the command substitution with $(...)
and quoted the expansion. Side note: if you can choose the datestamp format, I'd strongly recommend using +%F
(or %Y%m%d
) instead so it sorts chronologically.
With your paths and escaped for a cron job (do you really want to run this every minute?):
* * * * * mv /home/cbd_dev/CBD_DATA.zip "/home/sundaram_srivastava/archives/CBD_DATA_$(date +\%d\%m\%y).zip"