1

I want to copy (overwrite) folders from one directory to another set of directories, only if the folders in directory1 exist in directory2.

For example, I have stored some folders in my home directory:

home
    |admin
        |updates
            |package1
            |package2
            |package3

I also have another folder with builds of an app:

home
    |builds
        |build1
            |packages
                |package1
                |package2
                |package3
        |build2
            |packages
                |package1
                |package3
        |build3
            |rev1
                |packages
                    |package1
            |rev2
                |packages
                    |package2

I want the 'package1', 'package2', 'package3' folders found in '/home/updates/package' directory to be copied over to the 'packages' folders found recursively in '/home/builds' directory, but only if the folders already exist.

So in the example above, 'package1'/'package2'/'package3' would be copied into '/home/builds/build1/packages'. Only 'package1' would be copied into '/home/builds/build3/rev1/packages' ('package2'/'package3' would not because it doesn't exist there).

In addition, 'build1'/'build2'/'build3' may have different owner/group permissions so I would like to retain the relative target directory's permissions.

2 Answers 2

0
mkdir -p test/updates/pack1
...
mkdir -p test/builds/builds1/packages/pack3
...
touch test/updates/pack1/f1-1
...

run this command

find test/builds -type d  -name packages -exec bash -c 'for pk in "$1"/pack* ; do cp -r test/updates/"${pk##*/}" $1 ; done' none {} \;

Greetings

1
  • Thank you, this is awesome! I just need to find a way to preserve the target permissions; might just store them at the beginning of the script and then reapply them after the files are copied over. Many thanks! Commented Aug 27, 2019 at 14:26
0
for i in package1 package2 package3; do find /home/ -name $i -type d -not -path "/home/admin/updates/$i" -exec cp /home/admin/updates/$i/* {} \;; done
  • for i in package1 package2 package3; ... ; done - iterate through the names of the folders

  • find /home/ -name $i -type d - recursively find all the folders with said names in the /home/ directory

  • -not -path "/home/admin/updates/$i" - exclude from find results the original directory

  • -exec cp /home/admin/updates/$i/* {} \; - execute the command - copy files from original folder to found folder

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.