how do you copy a directory and its contents to a new location under a new directory name?

I'm new to the Linux command line and am trying to get to grips with the copy command at the moment.

Can anyone please tell me if it's possible to copy a directory with its subdirectories and associated files to a new directory with a new name, e.g. directory_backup?

Thanks for any and all help in advance.


You can use cp with the -r (copy recursively) flag and specify the new directory name:

cp -r /path/to/directory /path/to/location/new-name

In the above command replace the given paths with the real ones.

For example, to copy stuff from my home directory to an existing directory named backup and name the new directory stuff-backup (if this directory already exists, note that stuff will be copied into it, not overwrite it), you run:

cp -r ~/stuff ~/backup/stuff-backup

~ is a shortcut for your home directory /home/$USER or /home/zanna in my case. You can omit it if the current working directory is your home directory - you can see this from your prompt

zanna@monster:~$
              ^--the ~ here is where I am - home!

You can add the -v (verbose) flag to make cp report each copy being performed:

$ cp -vr stuff backup/stuff-backup
'stuff/thing1' -> 'backup/stuff-backup/thing1'
'stuff/thing2' -> 'backup/stuff-backup/thing2
...

The command you need is simply cp which stands for "copy".

You can use it for example with one of these syntaxes:

cp SOURCEFILE TARGETFILE
cp SOURCEFILE TARGETDIRECTORY

The first variant allows you to specify a new file name for the target file, while the second variant creates a copy with the same name in the target directory. You must of course substitute the place holders in capital letters with valid paths first.

However, cp by default operates on files only, not on directories. To get it to copy a complete directory with all its content recursively, you must add the -r option:

cp -r SOURCEDIRECTORY TARGETDIRECTORY

You can learn more about the cp command by typing man cp in your terminal.


As an alternative to the generally useful cp command you can use rsync which has the added benefit of replicating the permissions/timestamps of the original directory structure:

rsync -av dir/ newdir

-a archive -v verbose

note the slash after the source dir.