I have four types of files:

  • JUST_SOURCE exist only in the source directory
  • JUST_TARGET exist only in the target directory
  • SAME exist in in both source and target directories, and have the same checksum
  • DIFFERENT exist in in both source and target directories, but have different checksums

I want to do the following to each of them:

  • JUST_SOURCE move to target
  • JUST_TARGET do nothing
  • SAME remove from source
  • DIFFERENT do nothing

How can I do that from the command line? I have tried many possibililies with rsync but they didn't work.

  • It will be easier to understand this with example. This can be achieved with bash script!! Commented Mar 20, 2019 at 13:57

1 Answer 1


You have two things to do:

1) files in source not in target:

 mv -n "$source"/* $target

-n prevents overwriting if target exists, so you copy everything and mv -n will do the existence check for you

2) files in target with identical file in source, remove file in source

 for tgt in $target/* ; do src="$source"/$(basename "$f") ; cmp "$tgt" "$src" && rm "$src" ; done

cmp returns 0 (true, for bash) if the files are identical, 1 (false) if different, so bash evaluates only the first term of the && if it is false (false && anything is always false) and won't do the rm if the files are different.

  • Thank you very much. I didn't specify in the question because I thought it was not relevant: the files are in a directory structure. Could you please adapt the answer to deal with directories recursively?
    – toliveira
    Commented Mar 20, 2019 at 14:31
  • Then you have to iterate the directories and use that on each. I would have suggested rsync but your rule to not update a file which is different on source and target make that very difficult, since updating target to match source if they differ is what rsync is all about... But I don't see the point of your use case, since at the end you have random files left on source. Maybe you should amend your rules and look into rsync's --backup-dir and --suffix options to create backup copies of the target if it exists.
    – xenoid
    Commented Mar 20, 2019 at 15:35
  • About the use case I described: I wanted to move the directory from one disk to another. The target disk should be simply a backup, and files in it were not intended to be edited. However, some of the files were changed and a one by one analysis of them was needed to understand the changes, and how to merge them. At the end, the files left on source are not random, they are those that require analysis because they are already present on target but differ.
    – toliveira
    Commented Mar 20, 2019 at 18:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .