SigGP
SigGP

Reputation: 776

How to synchronize two folders in Bash?

I am writing a short script. One functionality is synchronizing two folders. Now I have two variables with directories to two different folder: DIRECTORY_1 and DIRECTORY_2. In both folders are files and other folders. I need to synchronize these folder to have all files in both folders. For example:

  1. In DIRECTORY_1 I have file1, file2, file3 and folder1
  2. In DIRECTORY_2 I have file4, file5, file6 and folder2

  3. I need comment after which I will have in both directories files1-6 and folders1-2.

I was trying rsync command but it doesn't work properly.

Upvotes: 2

Views: 2045

Answers (3)

blackghost
blackghost

Reputation: 1825

Likely not the most efficient, but this would do the trick:

comm <(ls DIR1) <(ls DIR2) -23 | while read f; do cp -r DIR2/$f DIR1; done
comm <(ls DIR1) <(ls DIR2) -13 | while read f; do cp -r DIR1/$f DIR2; done

Upvotes: 1

i love mistaking
i love mistaking

Reputation: 103

Use unison, it's a real folder synchroniser (such as Dropbox or Mega did).

https://www.cis.upenn.edu/~bcpierce/unison/

Mac installation with brew:

 brew install unison

I used this command:

unison -auto /path/folder1 /path/folder2

Moreover, and most important to me, if 2 files have the same name, it replaces with the most recent version.

Upvotes: 1

James Brown
James Brown

Reputation: 37404

$ mkdir dir1
$ mkdir dir2
$ touch dir1/file1 dir1/file2 dir1/file3
$ mkdir dir1/folder1
$ touch dir2/file4 dir2/file5 dir2/file6
$ mkdir dir2/folder2
$ tree
.
|-- dir1
|   |-- file1
|   |-- file2
|   |-- file3
|   `-- folder1
`-- dir2
    |-- file4
    |-- file5
    |-- file6
    `-- folder2
$ rsync -a dir1/ dir2
$ tree
.
|-- dir1
|   |-- file1
|   |-- file2
|   |-- file3
|   `-- folder1
`-- dir2
    |-- file1
    |-- file2
    |-- file3
    |-- file4
    |-- file5
    |-- file6
    |-- folder1
    `-- folder2

I guess rsync -d dir2/ dir1 would be next?

Upvotes: 3

Related Questions