Copy every file in a directory structure into specific path only if file does not exist there already
You can use -u
switch from cp
command:
copy only when the SOURCE file is newer than the destination file or when the destination file is missing
or use rsync
command with --ignore-existing
:
skip updating files that exist on receiver
Example:
rsync --ignore-existing source/* destination/
Your original command can be rewritten as:
find . -type f -exec bash -c 'test -e /target-directory/"$1" || cp "$1" /target-directory' sh {} \;
The key here is that we call shell with specific commands and pass found file as $1
argument. If test -e /target-directory/"$1"
fails, that means file doesn't exist, in which case cp
will copy the file.
In general, one can use other commands, as long as the command can verify existence of a file. Some of the other alternatives:
/usr/bin/realpath -e /target-directory/"$1" > /dev/null || cp "$1" /target-directory
stat >/dev/null /target-directory/"$1" || cp "$1" /target-directory/"$1"