Tar only the Directory structure

后端 未结 5 1758
不知归路
不知归路 2021-02-13 13:26

I want to copy my directory structure excluding the files. Is there any option in the tar to ignore all files and copy only the Directories recursively.

5条回答
  •  难免孤独
    2021-02-13 13:59

    Directory names that contain spaces or other special characters may require extra attention. For example:

    $ mkdir -p "backup/My Documents/stuff"
    $ find backup/ -type d | xargs tar cf directory-structure.tar --no-recursion
    tar: backup/My: Cannot stat: No such file or directory
    tar: Documents: Cannot stat: No such file or directory
    tar: backup/My: Cannot stat: No such file or directory
    tar: Documents/stuff: Cannot stat: No such file or directory
    tar: Exiting with failure status due to previous errors
    

    Here are some variations to handle these cases of "unusual" directory names:

    $ find backup/ -type d -print0 | xargs -0 tar cf directory-structure.tar --no-recursion
    

    Using -print0 with find will emit filenames as null-terminated strings; with -0 xargs will interpret arguments that same way. Using null as a terminator helps ensure that even filenames with spaces and newlines will be interpreted correctly.

    It's also possible to pipe results straight from find to tar:

    $ find backup/ -type d | tar cf directory-structure.tar -T - --no-recursion
    

    Invoking tar with -T - (or --files-from -) will cause it to read filenames from stdin, expecting each filename to be separated by a line break.

    For maximum effect this can be combined with options for null-terminated strings:

    $ find . -type d -print0 | tar cf directory-structure.tar --null --files-from - --no-recursion
    

    Of these I consider this last version to be the most robust, because it supports both unusual filenames and (unlike xargs) is not inherently limited by system command-line sizes. (see xargs --show-limits)

提交回复
热议问题