Copy all files in a directory to a local subdirectory in linux

I have a directory with the following structure:

# etc.


I would like to make a copy of all existing files and directories located in this directory into new_subdir

. How can I accomplish this via linux terminal?


source to share

3 answers

This is an old question, but none of the answers work (they cause the destination folder to be copied to itself recursively), so I figured I'd offer some working examples:

Copy via find -exec:

find . ! -regex '.*/new_subdir' ! -regex '.' -exec cp -r '{}' new_subdir \;

This code uses regex to find all files and directories (in the current directory) that are not new_subdir and copies them to new_subdir. The bit ! -regex '.'

is there to not include the current directory. Using find is the most powerful technique I know, but it is durable and a little confusing.

Copy with extglob:

cp -r !(new_subdir) new_subdir

If you have extglob enabled for your bash terminal (which you probably do), then you can use! to copy all things in the current directory that are not new_subdir to new_subdir.

Copy without extglob:

mv * new_subdir ; cp -r new_subdir/* .

If you don't have extglob, and you don't like searching, and you really want to do something hacky, you can move all the files to a subdirectory and then recursively copy them back to the original directory. Unlike cp, which copies the target folder to itself, mv just throws an error when it tries to move the destination folder inside of itself. (But it successfully moves all other files and folders.)



Do you mean

cp -R * new_subdir




take -R

as an argument which means recursive (so copy directories too) *

means all files (and directories).

Although it *

includes new_subdir

itself, it cp

detects this case and ignores it new_subdir

(so it doesn't copy it to itself!)



Try something like:

 cp -R * /path_to_new_dir/




All Articles