How to Copy a File or Directory in Linux

In this article, we show how to copy a file or directory in linux.
So in order to make a copy a file or directory, we use the cp command in linux.
The cp command copies files or directories.
How to Copy a File
To copy a single file named file1.txt and make the
copied file name file1copy.txt, we use the following code below.
So the code above makes a copy of the file, file1.txt, and the name of the copy of the file is file1copy.txt
In order to make a copy of multiple files and place them in a directory, we can specify after the cp command the names of the files followed lastly by the directory we want to place these copied files to.
In the following code below, we make a copy of
file1.txt, file2.txt and file3.txt and place them in the
NewDirectory folder.
So now we made a copy of
file1.txt, file2.txt, and file3.txt
and placed these copied files in the NewDirectory
folder.
How to Copy a Directory
Next, we show how to copy a directory and its content to another directory.
To copy a directory, directory1 (and its contents)
to directory, directory2, we use the line shown below.
This copies directory1 (its contents) to directory2. If directory2 does not exist, it is created and will contain the same contents as directory1.
cp -r stands for recursive. This cp option recursively copies directories and their contents. This option (or the -a option) is required when copying directories.
Another option for copying a directory is shown
in the code below.
Using a wildcard, all the files in directory1 are copied into directory2. directory2 must already exist.
Below is a table for cp command options.
Option | Meaning |
-a, --archive | Copy the files and directories and all of their attributes, including ownerships and permissions. Normally, copies take on the default attributes of the user performing the copy. |
-i, --interactive | Before overwriting an existing file, prompt the user for confirmation. If this option is not specified, cp will silently overwrite files. |
-r, --recursive | Recursively copy directories and their contents. This option (or the -a option) is required when copying directories. |
-u, --update | When copying files from one directory to another, copy only files that either don't exist or are newer than the existing corresponding files in the destination directory. |
-v, --verbose | Display informative messages as the copy is performed. |
So these are the various options for the cp command.
And this is how to copy a file or directory in linux.
Related Resources
How to Randomly Select From or Shuffle a List in Python