Linux Command: cp (Copy)

Published on September 12, 2023 at 10:51 am by LEW

Introduction

The cp command is part of the Linux Core Utilities. It can be thought of as an acronym for copy or copy-paste if you like. It is used to create copies of files and directories.

Note that for this post we are using the bash shell.

It was introduced in version 1 Unix in 1971. It is part of the GNU Core Utilities, announced in 1990, and available on Unix/Linux Operating Systems (OS)

Available through the Command Line Interface (CLI), cp is one of the more common commands you will be using from a terminal.

Syntax and Function

The syntax of the cp command is:

cp [options] Source Destination

Usage

The cp command has several modes, depending on the Source and Destination strings entered;

Options

Listed here are some of the more common options used with cp.

Options can be strung together or used individually. “-f -r” is the same as “-fb”.

Examples

Copy file and change name of copy: Lets say we have a file called “testfile1.txt”. Before modifying the file, we want to create a backup copy. Lets further assuming we are in the directory containing the file, and do not need path information. To make a backup copy we enter the filename as the source, and a different file name as the destination, “testfile1.txt.bak”.

cp testfile1.txt testfile1.bak.txt

Copy a file to another directory: Lets assume we are in our home directory, and we have two folders named project and backup. To copy the file “test.txt” from the project folder to the backup folder, keeping the same name, use the command below. Note that since we are in a directory containing the two folders, we only need to specify the path from our location.

cp project/test.txt backup/test.txt

Copy an entire Directory using absolute paths: Lets assume we have a project folder called “projectA1”in /home/user/projects. We want to copy the entire directory to /srv/backups. Lets also assume we want some feedback as it is being copied, and that there are folders within our project. We add the -v and -r optiosn for verbose and recursive.

cp -vr /home/user/projects/projectA1 /srv/backups/projectA1.bak

Using a wild cards: The cp command supports wild cards. Lets assume we have a source folder; ~/photos (~ is a shortcut for our home directory) containing a number of photos in the jpg format containing the term “wallpaper”. We want to copy them over to /usr/share/wallpaper (note this will require administrative permissions and we will assume sudo for this example).

sudo cp /home/user/*wallpaper*.jpg /usr/share/wallpaper

Conclusion

The cp command (as part of core utilities) is something every Linux/Unix surer should know, regardless if you rarely use a terminal or are in it everyday. In many instances it can be faster and more powerful than its GUI counter parts.

It is well worth your time to learn to use the cp command.

Add New Comment

Your email address will not be published. Required fields are marked *