Copy Files on Linux and BSD (cp command with examples)

Written by
Date: 2015-05-30 10:25:32 00:00

Spanish

How to copy files on Linux or BSD systems from one location to another on the same computer? How to copy files and directories (folders) on Linux and BSD systems?

The answer to the questions above is solved with the cp command, cp stands for copy and it is the command you have to use to copy files from one location to another if you are using Unix, Linux or BSD like FreeBSD or Mac OS X operating systems. This command will copy the file from one site to another on the same computer, or at least to file systems attached to that computer it could of course be a network file system so it is technically not the same computer.

How to use cp to copy files

Syntax

cp [options] [source file] [target file]
cp [options] [source file] [target directory]

How to copy a file from on place to another, one folder to another.

Let’s say you want to copy archive.txt from /home/user/peter/ to /home/user/backup/

cp /home/user/peter/archive.txt /home/user/backup/

This command will keep archive.txt unchanged in /home/user/peter/ folder and create an exact copy in /home/user/backup/ folder. Actually is just an exact copy of the contents of the file, because the attributes are changed, if you want them unchanged you have to use -p option.

cp -p /home/user/peter/archive.txt /home/user/backup/

From the BSD man page:

-p
Cause cp to preserve the following attributes of each source file in the copy: modification time, access time, file flags, file mode, ACL, user ID, and group ID, as allowed by permissions.

So that is for BSD like systems, i.e. FreeBSD, OpenBSD and Mac OS X.

On Linux systems:

-p
same as —preserve=mode,ownership,timestamps
—preserve[=ATTR_LIST]
preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all

How to copy a file from one place to the same one, or another but with different name

If you want to change the name and the location or keep location and only copy the file with another name this is the way to do it.

cp /home/user/peter/archive.txt /home/user/peter/archive-original.txt

This way you have to files with the same content, this is a good practice on configuration files you want to change, that way you have a copy unchanged in case your changes screw the file.

Copy folder’s content recursively.

If you want to copy all contents of a folder do it this way.

cp /home/user/* /home/user/backup/

All files not recursively will be copied from /home/user/ to /home/user/backup/

cp -R /home/user/folder /home/user/backup/

This the directory folder itself and its contents will recursively be copied to /home/user/backup/

Finally, if you want to copy all contentes recursively but not the folder itself.

cp -R /home/user/folder/* /home/user/backup/