2

The sequence of commands

mkdir -p BASE/a/b/c && cp -a --target-directory=BASE/a/b/c /a/b/c/d

creates a subdirectory a/b/c under BASE, and then copies the directory tree at /a/b/c/d to BASE/a/b/c.

One problem with it is that it entails a lot of repetition, which invites errors.

I can roll a shell function that encapsulates this operation; for example, here's a sketch of it without any error checking/handling:

copytwig () {
    local source=$1
    local base=$2
    local target=$base/$( dirname $source )

    mkdir -p $target && cp -a --target-directory=$target $source
}

...but I was wondering if this could already be done with a "standard" Unix utility (where I'm using "standard" as shorthand for "likely to be found in a Unix system, or at least likely to be found in a Linux system").

2 Answers 2

3

With pax (a mandatory POSIX utility, though not installed by default in some GNU/Linux distributions yet):

pax -s':^:BASE/:' -pe -rw /a/b/c/d .

(note that neither --target-directory nor -a are standard cp options. Those are GNU extensions).

Note that with -pe (similar to GNU's -a), pax will try and copy the metadata (times, owner, permissions...) of the directory components as well (while BASE's metadata will be as if created with mkdir BASE).

2

You can use the --parents switch for cp to preserve the directory structure.

mkdir BASE && cp --parents -a --target-directory=BASE /a/b/c/d

Edit: sorry, you asked for a Unix solution, but this seems to be Linux only. :(

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .