Wednesday, February 23, 2022

[SOLVED] Linux: copy ".svn" directories recursively

Issue

I know there are dozen of questions about similar topcis but I still can't beat this up.

I need to copy all .svn directories recursively from /var/foo to /var/foo2 on a Debian machine:

/var/www/foo/.svn
/var/www/foo/bar/.svn
...

I tried these two commands without success:

find /var/foo -name ".svn" -type f -exec cp {} ./var/foo2 \;
find /var/foo -name ".svn" -type d -exec cp {} /var/foo2 \;

Once only the svn directory right inside foo is copied, while another time nothing is copied.


Solution

Given following file structure:

./
./a/
./a/test/
./a/test/2
./b/
./b/3
./test/
./test/1

Running following script in the directory to be copied:

find -type d -iname test -exec sh -c 'mkdir -p "$(dirname ~/tmp2/{})"; cp -r {}/ ~/tmp2/{}' \;

Should copy all test directories to ~/tmp2/.

Points of interest:

  • Directories are copied to the destination on a one-by-one basis
  • Parent directories are created in advance so that cp doesn't complain about target not existing
  • Rather than just cp, cp -r is used
  • The whole command is wrapped with sh -c so that operations on {} such as dirname can be performed (so that the shell expands it for each directory separately, rather than expanding it once during calling the find)

Resulting structure in ~/tmp2:

./
./a/
./a/test/
./a/test/2
./test/
./test/1

So all you should need to do is to replace test with .svn and ~/tmp2 with directory of choice. Just remember about running it in the source directory, instead of using absolute paths.



Answered By - rr-
Answer Checked By - David Goodson (WPSolving Volunteer)