Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  22] [ 0]  / answers: 1 / hits: 41868  / 1 Year ago, mon, may 15, 2023, 8:35:15

Is there a way to copy an entire directory, but only the folders? I have a corrupt file somewhere in my directory which is causing my hard disks to fail.



So instead of copying the corrupt file to another hard disk, I wanted to just copy the folders, because I have scripts that search for hundreds of folders, and I don't want to have to manually create them all.



I did search the cp manual, but couldn't see anything (I may have missed it)



Say I have this structure on my failed HDD:



dir1
files
dir2
files
files
dir4
dir3
files


All I a want is the directory structure, not any files at all.



So I'd end up with on the new HDD:



dir1
dir2
dir4
dir3


Hoping someone knows some tricks!


More From » directory

 Answers
6

If you want to mirror a directory skeleton and copy no files:



find -type d -links 2 -exec mkdir -p "/path/to/backup/{}" ;


What's going on here:




  • Find is only selecting directories

  • We're using -links 2 to find the deepest possible directories.

  • mkdir -p will make any missing directories along the way.



I've done it like this rather than find -type d -exec mkdir -p "/path/to/backup/{}" ; because it'll cut out on a whole buttload of mkdir calls. We can quickly prove this with a little test. Here's the test tree followed by what I ran to compare the two commands:



$ tree
.
├── dir1
│   ├── dir2
│   │   └── dir3
│   ├── dir7
│   └── dir8
└── dir9
└── dir0

$ pr -m -t <(find -type d) <(find -type d -links 2)
. ./dir1/dir8
./dir1 ./dir1/dir2/dir3
./dir1/dir8 ./dir1/dir7
./dir1/dir2 ./dir9/dir0
./dir1/dir2/dir3
./dir1/dir7
./dir9
./dir9/dir0


And that's only going to get better in a real-word solution with thousands of directories.


[#28738] Tuesday, May 16, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ithriv

Total Points: 46
Total Questions: 115
Total Answers: 96

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
ithriv questions
Tue, Mar 14, 23, 14:31, 1 Year ago
Wed, Oct 5, 22, 02:59, 2 Years ago
Fri, Mar 11, 22, 10:12, 2 Years ago
Thu, May 11, 23, 10:55, 1 Year ago
Sun, Sep 26, 21, 06:47, 3 Years ago
;