How to avoid 'are the same file' warning message when using cp in Linux?

Matkrupp picture Matkrupp · Aug 9, 2013 · Viewed 37.5k times · Source

I'm trying to copy certain files from one directory to another. Using this command

find "$HOME" -name '*.txt' -type f -print0 | xargs -0 cp -t $HOME/newdir

I get an warning message saying

cp: '/home/me/newdir/logfile.txt' and '/home/me/newdir/logfile.txt' are the same file

How to avoid this warning message?

Answer

user000001 picture user000001 · Aug 9, 2013

The problem is that you try to copy a file to itself. You can avoid it by excluding the destination directory from the results of the find command like this:

find "$HOME" -name '*.txt' -type f -not -path "$HOME/newdir/*" -print0 | xargs -0 cp -t "$HOME/newdir"