How to recreate a directory structure

By jbayer - Last updated: Tuesday, September 6, 2011 - Save & Share - Leave a Comment

While cloning a system into a virtual machine, I needed to recreate a fairly large directory structure with identical attributes.  Since there aren’t any specific commands I wrote the following script.

What it does is to use find to find all directories and print out a series of commands which are needed to recreate each directory.  I put the mkdir, chown and chmod onto separate lines for clarity, but you can combine them if you like.

The script is short enough that I’m listing it here.  Just copy and paste it into an editor, save it, and run it.

To run, you need to specify the initial directory at the only parameter on the command line, and redirect the output into a file.

# Given a directory path, find all subdirectories and create
# script which will recreate the directory structure identically, owners, groups and permissions

if [ "$1" = "" ]; then
        echo "Enter a directory to scan on the command line"

function create_mkdir()

        perms=`stat -c "%a" $dir`

        echo "mkdir -p $dir"
        echo "chown $owner.$group $dir"
        echo "chmod $perms $dir"

find $1 -type d -exec ls -ld {} \;  | sed "s/  / /g" | cut -f3,4,9 -d" " |
while read line
        set -- $line
        create_mkdir $1 $2 $3
        echo -ne "\n"
Posted in Administration • • Top Of Page

Write a comment