Copying files using the cp command - Bash

This article covers how to use the bash command cp.

If you want to copy files from one directory into another, you can use the cp command.

Copy to a different directory

The simplest way to call it is to specify the source path, and the new directory:

cp <source-path> <destination-directory>

For instance, to copy a file called test.txt over to a testFolder directory in the same folder, you would use:

cp test.txt ./testFolder/

Copy and rename

If you specify a name for the file in the destination, you can also change the name at the same time.

For instance:

cp test.txt ./testFolder/testClone.txt

This will copy the test.txt file into the testFolder directory, and rename it as testClone.txt.

Copy multiple files

Often, you will want to copy multiple files over to a single directory.

To do this, simply supply the list of sources (space-separated) before the destination directory.

For example:

cp test1.txt test2.txt test3.txt ./testFolder/

Copying all files within a directory

If you wish to copy all files within a directory to a new directory, you can use the * wildcard:

# Get all files and copy them to the testFolder
cp * ./testFolder/

Similarly, if we only wish to move files with a specific extension, or filename structure, we could specify the * wildcard as part of the source name:

# Get all text files and copy them to the testFolder
cp *.txt ./testFolder/

Note that this will not copy directories! To do so, you need to add the recursive option -R.

Copy all files and folders within a directory

To copy all files and folders within a directory, you need to specify the recursive option -R, which will tell the cp command to copy all files in all subdirectories also:

# Get all files and folders and copy them to the testFolder
cp -R * ./testFolder/

Preserving the file attributes

All files will have file attributes (such as modified date/time) associated with them.

When using the cp command, these attributes get replaced, unless you use the -p option:

cp -p test.txt ./testFolder/test.txt

The -p option will force the cp command to preserve the following attributes:

  • Modified date & time
  • Access time
  • File flags
  • File mode
  • User ID
  • Group ID
  • Access Control Lists
  • Extended Attributes