How to copy a file, group of files, or directory in Linux?

LinuxOperating SystemOpen Source

In this article, we will learn to copy a file or directory in the Linux/Unix operating system using terminal, we use the cp command to copy a file or directory in the Linux system.

cp (copy) - The cp command is used to copy files or directories in the Linux system. If we want to copy a file from a source directory and paste it into another destination directory then we have to use the cp command. By default, the cp command will not copy directories to copy directories we have to use -R option with cp command otherwise error will be prompt.

Syntax

The general syntax of the cp command is as follows −

cp [OPTION]...[-T] SOURCE DESTINATION
cp [OPTION]...SOURCE DESTINATION
cp [OPTION]...-t DIRECTORY SOURCE...

Brief description of option available in the cp command.

Sr.No.Option & Description
1--attributes-only 
Copy only attributes of file
2--backup
Create backup of destination file
3-b
Create backup file without argument
4-f
Copy forcefully
5-i, interactive
Prompt before overwriting files
6-l, --link
Create hard link of files instead of copying
7-R, -r, --recursive
Copy directories recursively
8--help
Displays a help message and then exits.
9--version
It gives info about the version and then exits.

We will copy a file from a directory and paste it into another directory using cp command

$ cp file.txt ../snow

After executing this command files will be copied, to ensure we will change the directory and list the contents of the directory using the below command.

$ cd ../snow
$ ls
file.txt

We will copy all .txt (text) files available in a source directory and paste it into the destination directory using * wildcard with cp command in the Linux system.

$ cp *.txt ../snow

Here, we use the -i option to copy a file from the source directory and paste it into the destination directory if the file is already existing in the destination directory with the same name then a warning message will be prompt before overriding the file.

$ cp -I file1.txt ../shadow
cp: overwrite ‘../shadow/file.txt’? y
raja
Published on 30-Jun-2021 10:53:57
Advertisements