2

Is there a way to check if cp -r would overwrite anything, without actually copying anything?

-n seems to copy files that don't collide, which is not what I want.

common sense
  • 3,775
  • 6
  • 22
  • 31
Filip Haglund
  • 13,919
  • 13
  • 64
  • 113
  • Possible duplicate of [Linux how to copy but not overwrite?](https://stackoverflow.com/questions/9392735/linux-how-to-copy-but-not-overwrite) – l'L'l Jan 01 '19 at 18:13
  • Cross-site duplicate: https://unix.stackexchange.com/questions/187937/how-to-test-which-files-will-be-copied-with-the-cp-command – tripleee Jan 02 '19 at 05:12

3 Answers3

2

The easiest way is to use the rsync command there you have a lot of parameters to override the target or delete files on the target if you want.

https://linux.die.net/man/1/rsync

or like mentioned in the comments you could use cp -n for --no-clobber. But in general i would suggest rsync there you have a lot more possibilities.

René Höhle
  • 26,716
  • 22
  • 73
  • 82
0

cp has the -i --interactive option and the -n, --no-clobber option. See `man 1 cp'.

0

To only check if the file exists in the target location, but not actually perform any copying you can use the diff command with the -r option.

From man diff:

-r, --recursive
recursively compare any subdirectories found

diff -r --brief --report-identical-files /source-folder/ /target-folder/ | grep -v '^Only in'
  • --brief is listing files that differ (same as -q)
  • --report-identical-files does the same for files that don't differ (same as -s)
  • The grep -v '^Only in' removes files that are only in one directory tree, because those will not be overwritten.

The output will look something like this:

Files /source-folder/file1.txt and /target-folder/file1.txt are identical
Files /source-folder/file2.jpg and /target-folder/file2.jpg differ
Samuel Kirschner
  • 1,135
  • 1
  • 12
  • 18