Open In App

How to Copy Files and Directories in Linux | cp Command

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the world of Linux computers, a common and important job is copying files. The key tool for this task is the “cp” command. In this simple guide, we’ll explore how to copy a file in Linux, looking at the basic steps, different choices you can make, and giving clear examples. We’ll also take a peek behind the scenes to understand how the “cp” command works. Let’s get started on this easy journey to become familiar with the ins and outs of copying files in Linux!

Syntax of cp Command

The basic syntax for copying a file using the cp command is as follows:

cp source_file destination

This command creates a copy of the `source_file` at the specified `destination`. If the destination is a directory, the file is copied into that directory.

How to Copy files in Linux with the cp Command

The `cp` command is a versatile tool used in Unix-like operating systems for copying files and directories. It offers three principal modes of operation, each serving different purposes.

1. Copying Between Two Files in Linux

If the `cp` command contains two file names, it copies the contents of the first file to the second file. If the second file doesn’t exist, it is created, and the content is copied into it. However, if the second file already exists, it is overwritten without warning.

cp Src_file Dest_file
  • If `Dest_file` does not exist, it is created.
  • If `Dest_file` already exists, it is overwritten without any warning.

Example 1:

  • Initially, there is only one file (`a.txt`) in the directory.
  • The `cp` command is used to copy the contents of `a.txt` to `b.txt`.
  • After the command execution, both `a.txt` and the newly created `b.txt` coexist in the directory.
cp a.txt b.txt
Copy a file in Linux

copy a file in Linux

We used `ls` command to display all the file in the current directory.

Example 2:

  • Initially, there are two files (`a.txt` and `c.txt`) in the directory.
  • The `cp` command is used to copy the contents of `a.txt` to `c.txt`.
  • After the command execution, the content of `c.txt` is overwritten with the content of `a.txt`.
cp a.txt c.txt
Copy a file in Linux

Copy a file in Linux

We used `ls` command to display all the file in the current directory and used `cat`command to display the content in the text file.

2. Copy files to a Directory in Linux

When the cp command has one or more source file arguments and is followed by a destination directory argument, it copies each source file to the destination directory with the same name. If the destination directory does not exist, it is created. If it already exists, the files are overwritten without warning.

cp Src_file1 Src_file2 Src_file3 Dest_directory

Example:

Suppose we have to copy three files name “a.txt“, “b.txt” and “c.txt” to a directory name “new

cp a.txt b.txt c.txt new/
Copy multiple files to another directory

Copy multiple files to another directory

We used `ls` command to display all the file in the “new” directory to confirm the successful copy of file in that directory.

3. How to Copy Directories in Linux

In this mode, if the cp command contains two directory names, it copies all files from the source directory to the destination directory. The `-R` option is typically used to indicate recursive copying for directories.

cp -R Src_directory Dest_directory
copying files between two directories

copying files between two directories

The behavior depends on whether `Dest_directory` exists or not. If it doesn’t exist, `cp` creates it and copies the content of `Src_directory` recursively. If `Dest_directory` exists, the copy of `Src_directory` becomes a sub-directory under `Dest_directory`

Options Available in cp Command in Linux

 There are many options of cp command, here we will discuss some of the useful options:

Option                           Detail
-i

Interactive copying with a warning before overwriting the destination file.

-b

Creates a backup of the destination file in the same folder with a different name and format.

-f

Forces copying, even if the user lacks writing permission; deletes destination file if necessary.

-r or -R

Copies directory structure recursively.                                        

-p

Preserves file characteristics (modification time, access time, ownership, permission-bits).

`*`

Uses the * wildcard to represent all files and directories matching a pattern.

1. Copy a File in Linux Using `-i` Option

-i(interactive): i stands for Interactive copying. With this option the system first warns the user before overwriting the destination file. cp prompts for a response, if you press y then it overwrites the file and with any other option leaves it uncopied.

Basic Syntax:

cp -i [Source_file] [Destination_file] 

Example:

cp -i a.txt b.txt    
Copy a File in Linux Using `-i`

Copy a File in Linux Using `-i`

Here,

  • `ls` command shows existing files: `a.txt` and `b.txt`.
  • `cat a.txt` displays the content of `a.txt`.
  • `cat b.txt` displays the content of `b.txt`.
  • `cp -i a.txt b.txt` initiates an interactive copy.
  • System prompts to confirm overwrite of` b.txt`.
  • User responds with ‘y’ to confirm.
  • `cat b.txt` shows the updated content, which now matches `a.txt`.

2. Copy a File in Linux Using `-f` Option

-f(force): If the system is unable to open destination file for writing operation because the user doesn’t have writing permission for this file then by using -f option with cp command, destination file is deleted first and then copying of content is done from source to destination file.

Basic Syntax:

cp -f [Source_file] [Destination_file]

Example:

cp -f a.txt b.txt
Copy a File in Linux Using `-f`

Copy a File in Linux Using `-f`

Here,

  • `ls` command shows existing files: `a.txt` and `b.txt`.
  • `cat a.txt` displays the content of `a.txt`.
  • `cat b.txt` displays the content of `b.txt`.
  • `cp -f a.txt b.txt` initiates a forceful copy.
  • Destination file (b.txt) is overwritten without prompting.
  • `cat b.txt` shows the updated content, which now matches `a.txt`.

3. Copy a File in Linux Using `-r` or `-R` Option

Copying directory structure recursively. With this option cp command shows its recursive behavior by copying the entire directory structure recursively.

Basic Syntax:

cp -r [Directory_name1] [Directory_name2]

Example:

cp -r geeksforgeeks gfg

4. Copy a File in Linux Using `-p` Option

-p(preserve): With -p option cp preserves the following characteristics of each source file in the corresponding destination file: the time of the last data modification and the time of the last access, the ownership (only if it has permissions to do this), and the file permission-bits. 

Note: For the preservation of characteristics, you must be the root user of the system, otherwise characteristics change.

Basic Syntax:

cp -p [Source_file] [Destination_file]

Example:

cp -p a.txt c.txt

5. Copy a File in Linux Using `*` Option

Copying using * wildcard: The star wildcard represents anything i.e., all files and directories. Suppose we have many texts documents in a directory and want to copy it to another directory, it takes lots of time if we copy files 1 by 1 or command becomes too long if specify all these file names as the argument, but by using * wildcard it becomes simple.

Basic Syntax:

cp *.txt [Destination Directory or file]

Example:

cp *.txt Folder1
Copy a File in Linux Using `*`

Copy a File in Linux Using `*`

Conclusion

The `cp` command is an essential tool which is used for copying files or groups of files and directories in Unix-Like operating systems. If we talk about its syntax it takes at least two filenames in as an argument (source and destination). As mentioned, the command has three principles: copying two file names, copying one or more arguments, and copying two directory names. Then we also mention the multiple options available while using `cp` command: `-i` , `-b` , `-f“ , `-r` , `-p`. To work with easy in Unix shell for file management one should know the proper working of `cp` command. 

How to Copy Files and Directories in Linux | cp Command – FAQs

How Do You Copy Files and Directories in Linux?

The cp command is used in Linux to copy files and directories from one location to another. Below are the steps and options commonly used with this command:

Copying Files

To copy a single file from one location to another, you can use:

cp source_file_path destination_file_path

For example:

cp /home/user/file1.txt /home/user/backup/file1.txt

This command copies file1.txt from the user directory to a backup directory.

Copying Directories

To copy a directory, including all its contents (files and subdirectories), you use the -r (recursive) option:

cp -r source_directory_path destination_directory_path

For example:

cp -r /home/user/documents /home/user/backup/documents

This copies the entire documents directory and its contents into the backup directory.

What Command is Used to Copy Files and Directories?

The cp command is used to copy both files and directories, often with various options to tailor its functionality:

  • -r: Recursive, for copying directories.
  • -a: Archive, similar to -r and preserves the structure and attributes of files but is generally used for backing up.
  • -v: Verbose, shows what cp is doing (useful for tracking what gets copied).

What is the cp -R Command in Linux?

The cp -R command is an alternative to cp -r, and it functions the same way by copying directories recursively. Some systems differentiate slightly in how they handle symbolic links and special files between -R and -r, but for most users and typical usage, they behave the same.

What is the cp Command in Terminal?

In the terminal, the cp command is used to copy files and directories:

  • Syntax: cp [options] source destination
  • Options: Modify behavior (like -r for recursive copy).

How Do I Copy a Directory?

To copy a directory in Linux, use the cp command with the -r option. Here’s how you might copy a directory from one place to another:

cp -r /path/to/original_directory /path/to/copy_directory

This command ensures that the entire directory, including all nested files and subdirectories, is copied to the new location.



Previous Article
Next Article

Similar Reads

Ways to Permanently and Securely Delete ‘Files and Directories’ in Linux
Linux is an open-source operating system that is loved by tech geeks. It is a versatile operating system that can be used on thousands of different hardware configurations. The most interesting feature of Linux is its command line interface. This feature allows you to perform multiple operations within the operating system with just a few commands.
8 min read
How to Copy a File to Multiple Directories in Linux
In this article, we will discuss how to copy a file to multiple directories in Linux. xargs, find, tee, shell loop, and parallel are the commands that can help you to copy a File to Multiple Directories. Suppose we have a file with the name "xyz.txt" and we want to copy it into 3 directories with the name dir1, dir2, and dir3 then we use the follow
5 min read
UrlBuster - Linux tool to find Web Hidden Files or Directories Finder
Hidden files and directories on the target server can contain some sensitive and crucial information about the target. This revealed information can also compromise the security of the application. To find these directories and files, we need an automated approach as manual testing would make a headache to the tester. UrlBuster is an automated tool
5 min read
How to Securely Copy Files in Linux | scp Command
scp (secure copy) command in Linux system is used to copy file(s) between servers in a secure way. The SCP command or secure copy allows the secure transferring of files between the local host and the remote host or between two remote hosts. It uses the same authentication and security as it is used in the Secure Shell (SSH) protocol. SCP is known
8 min read
How to Exclude Files and Directories When Creating a tar.gz File
GNU tar is a type of archiving program that is designed to store multiple files into a single file and to manipulate such archives. The archive can be either a regular file or a device that can be located either locally or on a remote machine. How to Exclude Files and Directories When Creating a tar.gz File Step 1: First we need to create multiple
2 min read
Systemd Services: Monitoring Files and Directories
It is very important to keep our services running smoothly in Linux system administration and management. Systemd is a versatile tool used in Linux that helps us manage our services and automate our tasks. It can also act as a watch guard to monitor files and directories using "path units". In this article, we will learn how to use Systemd to monit
5 min read
Find and Replace with sed in Directory and Sub Directories in Linux
sed stands for stream editor. It is a basic utility command in Linux that has basic functionality like inserting, deleting, finding, replacing, and searching text strings in a file. But sed is most commonly used for its substitution function i.e find and replace. Syntaxsed OPTIONS... [script] [input_file] e.g. sed "s/abc/ABC/g" abc.txt Consider the
4 min read
How to Sync File and Directories to Cloud Storage in Linux Using Rclone Tool?
Rclone is a command-line tool for synchronizing files and directories between Google Drive, Amazon S3, Openstack Swift / Rackspace cloud files / Memset Memstore, Dropbox, Google Cloud Storage, and the local filesystem. It is a single binary file that contains a Go program. Rclone is an MIT-licensed Free and Open Source Software that can be found in
3 min read
How to Recursively Grep all Directories and Subdirectories in Linux
In this article, we will demonstrate how to grep recursively through all directories and subdirectories. But before I do that, let me define what the term "grep" means. Basically, grep means searching or fetching. The grep is one of the basic utility commands of Linux systems. When one needs to determine whether a specific string is present in a te
3 min read
How to Transparently Overlaid Two Directories Using UnionFS in Linux?
To transparently overlay two directories one on top of the other using UnionFS following steps must be followed: Step 1: Enter into the superuser mode and install the unionfs-fuse package. $ apt install unionfs-fuse Step 2: Now create a dir1 directory and then create two files f1 and f2 inside that directory. $ mkdir /root/dir1 $ touch /root/dir1/f
1 min read
Linux Shell Script to Sync Directories Interactively
Scripts that sync directories are scripts used to synchronize the contents of two directories. This means that the script will ensure that the two directories have duplicate files and directories and that the contents of the files are the same. There are various ways to sync directories, and the specific approach depends on the requirements of the
7 min read
How to Manage Directories in Linux?
Directories in Linux or any operating system help to organize the data and files, which is then easier to find and manage. In this article, you will learn everything you will need to manage directories in Linux. We will try to cover every topic from creating, and copying to deleting the directories and many more. We will explore various topics, inc
6 min read
How to Extract and Copy Files from ISO Image in Linux?
The term ISO was derived from the ISO 9660 file system, which is commonly used by optical media. An ISO image is a full copy of everything contained on a physical optical disc, such as a CD, DVD, or Blu-ray disc, including the file system. There is no compression and they are a sector-by-sector copy of the disc. ISO images are designed to allow you
3 min read
How to Compress and Extract Files Using the tar Command on Linux
An archive is a special file that contains any number of files inside. It can be restored via special programs, for example, tar.inside. .tar - archive files are usually not compressed..tar.gz - archive file compressed with gzip tool.tar.bz2 - archive file compressed with bzip2 tool Syntax: tar options [archive_name.tar] files_to_archive The tar co
2 min read
How To Copy Command Output To Linux Clipboard Directly
To copy commands outputs directly to Linux Clipboard we will be using a Program called xclip. xclip is a program that allows us to clip-> copy/crop ->cut and external reference or a block to a specific area. xclip reads text from standard inputs or files and make it available to other application for passing an X section. It reads from all fi
4 min read
Linux - Installing locate Command to Find Files
In this article, we will see how to install locate command to find files in Linux. locate is a command-line interface tool used for finding files by name in Linux systems. This works more efficiently than other commands. It uses one or more databases by updatedb. To check whether locate utility is already installed in your system. Open up your term
2 min read
How to List Open Files in Linux | lsof Command
In the world of Linux, understanding and managing open files is crucial for system administrators and users alike. The Linux operating system provides a powerful utility called lsof (List Open Files) that allows users to gain insights into the files currently open on their system. In this article, we will delve into the intricacies of the lsof comm
7 min read
How to Compress Files in Linux | Tar Command
File compression is a fundamental task in managing and transferring data efficiently on a Linux system. The Tar command, short for Tape Archive, is a powerful tool that allows users to create compressed and archived files. In this comprehensive guide, we will explore the various options and examples of using the Tar command to compress files on a L
11 min read
How to Compare Files Line by Line in Linux | diff Command
In the world of Linux, managing and comparing files is a common task for system administrators and developers alike. The ability to compare files line by line is crucial for identifying differences, debugging code, and ensuring the integrity of data. One powerful tool that facilitates this process is the diff command. In this article, we will explo
9 min read
How to sort lines in text files in Linux | sort Command
SORT command is used to sort a file, arranging the records in a particular order. By default, the sort command sorts file assuming the contents are ASCII. Using options in the sort command can also be used to sort numerically.  SORT command sorts the contents of a text file, line by line.sort is a standard command-line program that prints the lines
7 min read
Ccat – Colorize Cat Command Output command in Linux with Examples
ccat is a command-line tool for Linux and OSX, which is similar to the cat command in Linux. But the difference between cat and ccat is that the ccat shows the content of the file with the syntax highlighted. Currently, ccat supports the following programming languages. JavaScriptJavaRubyPythonGoCJSONInstallation of Ccat First, we are going to see
2 min read
How to Display Command History in Linux | history Command
The command-line interface in Linux provides powerful tools for users, and mastering command history is essential for efficient navigation and retrieval of previously executed commands. The history command is a valuable utility that allows users to view and search through their command history. In this comprehensive guide, we will explore the vario
4 min read
Exodus - Copy Linux Binaries From One Linux System
Exodus is an easy-to-implement program, that is used for bundling dependencies, and also helps to effectively copy Linux ELF binaries from one to another machine securely, and this is very handy when you don't have root access, also if there are issues in the availability of the packages in the Linux distribution, Commonly Server oriented distribut
3 min read
URLBrute – Tool to Brute Forcing Website Sub-Domains and Directories
Brute-Forcing is the technique of matching the credentials like Usernames, Passwords, OTPs for unauthenticated access to the target domain. The list of words are been tested against the target to get the exact credentials. All this process is done through automated tools. URLBrute is an automated tool developed in the Golang language which can be b
2 min read
DircoverRB - Passive subdomains and web directories recon using Bing
Google search engine preferably dislikes the scrapers which are used for the information collection or for crawling. So to get the information Bing search engine is been used. DircoverRB is an automated cyber security tool developed in the Ruby language which finds the passive subdomains and also discovers the directories of the target domain. The
2 min read
How to Find Difference Between Two Directories Using Diff and Meld Tools
The diff is a straightforward, original Unix command-line utility that displays the differences between two computer files. It compares files line by line, is simple to use, and is preinstalled on the majority, if not all, Linux distributions. How can we determine the differences between two folders in Linux is the query. Here, we're interested in
2 min read
How to Find Hidden Web Directories with Dirsearch
Dirsearch tool is a Python language-based tool, which is command-line only. Dirsearch lights when it comes to recursive scanning, so for every directory it identifies, it will go back through and crawl the directory for some additional directories. Dirsearch tool is an advanced command-line tool designed to brute-force directories and files in web
3 min read
Shell Script To Show Names of All Sub-Directories Present in Current Directory
In this given program, we are required to write a shell script to print the list of all the sub-directories present in the current directory. Currently, when we are running this program, the terminal is opened at the root directory location and hence, we are getting a list of sub-directories present at the root level. Moreover, this script comes in
2 min read
Dirhunt - Find Web Directories Without Bruteforce
Web directories and files can contain some sensitive data like API Keys or Usernames and Passwords or sometimes SSH Keys. So to get the links to these files and directories we need to use automated tools. Dirhunt tool is an automated cyber security tool that acts as a web crawler for searching directories on a web application. It also detects the 4
2 min read
Copy and Create Destination Directory if it Does Not Exist in Linux
A directory is a file system location for storing and organizing files. A Linux system has many directories, and users can create their own directories. Copying and creating a directory are useful operations for Linux users. To create a new directory, use the command: mkdir new_directory. The 'm' stands for 'modify.' The name of the new directory m
6 min read