[linux] Copy folder structure (without files) from one location to another

I want to create a clone of the structure of our multi-terabyte file server. I know that cp --parents can move a file and it's parent structure, but is there any way to copy the directory structure intact?

I want to copy to a linux system and our file server is CIFS mounted there.

This question is related to linux file copy directory

The answer is


This copy the directories and files attributes, but not the files data:

cp -R --attributes-only SOURCE DEST

Then you can delete the files attributes if you are not interested in them:

find DEST -type f -exec rm {} \;

Substitute target_dir and source_dir with the appropriate values:

cd target_dir && (cd source_dir; find . -type d ! -name .) | xargs -i mkdir -p "{}"

Tested on OSX+Ubuntu.


1 line solution:

find . -type d -exec mkdir -p /path/to/copy/directory/tree/{} \;

This works:

find ./<SOURCE_DIR>/ -type d | sed 's/\.\/<SOURCE_DIR>//g' | xargs -I {} mkdir -p <DEST_DIR>"/{}"

Just replace SOURCE_DIR and DEST_DIR.


A python script from Sergiy Kolodyazhnyy posted on Copy only folders not files?:

#!/usr/bin/env python
import os,sys
dirs=[ r for r,s,f in os.walk(".") if r != "."]
for i in dirs:
    os.makedirs(os.path.join(sys.argv[1],i)) 

or from the shell:

python -c 'import os,sys;dirs=[ r for r,s,f in os.walk(".") if r != "."];[os.makedirs(os.path.join(sys.argv[1],i)) for i in dirs]' ~/new_destination

FYI:


Here is a solution in php that:

  • copies the directories (not recursively, only one level)
  • preserves permissions
  • unlike the rsync solution, is fast even with directories containing thousands of files as it does not even go into the folders
  • has no problems with spaces
  • should be easy to read and adjust

Create a file like syncDirs.php with this content:

<?php
foreach (new DirectoryIterator($argv[1]) as $f) {
    if($f->isDot() || !$f->isDir()) continue;
        mkdir($argv[2].'/'.$f->getFilename(), $f->getPerms());
        chown($argv[2].'/'.$f->getFilename(), $f->getOwner());
        chgrp($argv[2].'/'.$f->getFilename(), $f->getGroup());
}

Run it as user that has enough rights:

sudo php syncDirs.php /var/source /var/destination


This solves even the problem with whitespaces:

In the original/source dir:

find . -type d -exec echo "'{}'" \; > dirs2.txt

then recreate it in the newly created dir:

mkdir -p <../<SOURCEDIR>/dirs2.txt

find source/ -type f  | rsync -a --exclude-from - source/ target/

Copy dir only with associated permission and ownership


Another approach is use the tree which is pretty handy and navigating directory trees based on its strong options. There are options for directory only, exclude empty directories, exclude names with pattern, include only names with pattern, etc. Check out man tree

Advantage: you can edit or review the list, or if you do a lot of scripting and create a batch of empty directories frequently

Approach: create a list of directories using tree, use that list as an arguments input to mkdir

tree -dfi --noreport > some_dir_file.txt

-dfi lists only directories, prints full path for each name, makes tree not print the indentation lines,

--noreport Omits printing of the file and directory report at the end of the tree listing, just to make the output file not contain any fluff

Then go to the destination where you want the empty directories and execute

xargs mkdir < some_dir_file.txt

cd /path/to/directories &&
find . -type d -exec mkdir -p -- /path/to/backup/{} \;

Here is a simple solution using rsync:

rsync -av -f"+ */" -f"- *" "$source" "$target"
  • one line
  • no problems with spaces
  • preserve permissions

I found this solution there


If you can get access from a Windows machine, you can use xcopy with /T and /E to copy just the folder structure (the /E includes empty folders)

http://ss64.com/nt/xcopy.html

[EDIT!]

This one uses rsync to recreate the directory structure but without the files. http://psung.blogspot.com/2008/05/copying-directory-trees-with-rsync.html

Might actually be better :)


The following solution worked well for me in various environments:

sourceDir="some/directory"
targetDir="any/other/directory"

find "$sourceDir" -type d | sed -e "s?$sourceDir?$targetDir?" | xargs mkdir -p

I dunno if you are looking for a solution on Linux. If so, you can try this:

$ mkdir destdir
$ cd sourcedir
$ find . -type d | cpio -pdvm destdir

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to copy

Copying files to a container with Docker Compose Copy filtered data to another sheet using VBA Copy output of a JavaScript variable to the clipboard Dockerfile copy keep subdirectory structure Using a batch to copy from network drive to C: or D: drive Copying HTML code in Google Chrome's inspect element What is the difference between `sorted(list)` vs `list.sort()`? How to export all data from table to an insertable sql format? scp copy directory to another server with private key auth How to properly -filter multiple strings in a PowerShell copy script

Examples related to directory

Moving all files from one directory to another using Python What is the reason for the error message "System cannot find the path specified"? Get folder name of the file in Python How to rename a directory/folder on GitHub website? Change directory in Node.js command prompt Get the directory from a file path in java (android) python: get directory two levels up How to add 'libs' folder in Android Studio? How to create a directory using Ansible Troubleshooting misplaced .git directory (nothing to commit)