Shell – Find files newer than a day and copy

shell-script

I am working on a script that will copy ONLY files that have been created within the last day off to another folder. The issue I am having is the script I have copies all of the files in the source directory instead of just the files less than a day old.

This is what I have:

find . -mtime -1 -exec cp --preserve --parents -a "{}" /somefolder \;

The above code copies all of the files in the source directory. If I remove all of the arguments for 'cp' then it works:

find . -mtime -1 -exec cp "{}" /somefolder \;

The above code copies only the newest files as I want but I need to preserve the attributes using the cp arguments.

I have also tried variables and for loops thinking maybe the -exec option was the issue:

files="$(find -mtime -1)"
for file in "$files"
do
cp --parents --preserve -a file /somefolder

However, the above for loop results in the same issue, all files are copied. If I echo $files only the files I need are shown.

How can I get this to work?

Best Answer

Some implementations of cp have a -t option, so you can put the target directory before the files:

find . -mtime -1 -exec cp -a --parents -t /somefolder "{}" \+

Note that -a implies --preserve so I removed the latter.

Related Question