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.
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.
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.
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