DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Copy Directory Tree With Tar

04.29.2009
| 6434 views |
  • submit to reddit
        If you want to copy a whole directory you can use "cp -a", but what if you want to copy only certain files/directories for a tree and keep that structure on destination? 

#!/bin/sh
#
# Usage: tarcopy tarjet source1 [source2] [...]
#
# Copy source files to target keeping directory structure
#  
# Example: tarcopy /tmp/destination /etc/file1 /etc/file2 /etc/dir1/file3 /etc/dir2
#
TARGET=$1
shift
tar cf - "$@" | \
  ( mkdir -p "$TARGET" && cd "$TARGET" && tar xfp -)