views:

42

answers:

3

In bash I need to do this:

  1. take all files in a directory

  2. copy them into an existing directory

How do I do this? I tried cp -r t1 t2 (both t1 and t2 are existing directories, t1 has files in it) but it created a directory called t1 inside t2, I don't want that, I need the files in t1 to go directly inside t2. How do I do this?

+1  A: 
cp dir1/* dir2

Or if you have directories inside dir1 that you'd want to copy as well

cp -r dir1/* dir2
Bertrand Marron
Depending on how your shell is configured, you'll probably need to use "dir1/* dir1/.*" instead of "dir1/*" if you want to also catch hidden files.
ssokolow
Copying `dir1/.*` is not a good idea, as it copies dir1/.. (i.e. the parent of the directory you're actually trying to copy). It also copies dir1/. which is fine, except that it's already (mostly) been copied, so you're doing the work twice.
Gordon Davisson
A: 
cp -R t1/ t2

The trailing slash on the source directory changes the semantics slightly, so it copies the contents but not the directory itself. It also avoids the problems with globbing and invisible files that Bertrand's answer has (copying t1/* misses invisible files, copying `t1/* t1/.*' copies t1/. and t1/.., which you don't want).

Gordon Davisson
A: 

Depending on some details you might need to do something like this:

r=$(pwd)
case "$TARG" in
    /*) p=$r;;
    *) p="";;
    esac
cd "$SRC" && cp -r . "$p/$TARG"
cd "$r"

... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.

The extra fussing is to handle relative or absolute targets.

(This doesn't rely on subtle semantics of the cp command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp and I don't know if they'll continue to be so in the future).

Jim Dennis