Over a million developers have joined DZone.

Copy Directory Tree With Tar

·
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 -)
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}