Linux cp Command
Let's go through some examples of the cp
command with output to demonstrate how it behaves in different scenarios. I'll use the -v
(verbose) option to show detailed output as the files are copied.
Example 1: Basic Copy of a Single File with Verbose Output
When copying a file, the -v
option provides feedback on the operation.
Command:
Output:
This indicates that file1.txt
has been copied to /home/user/Documents/
.
Example 2: Copy and Rename a File
To rename a file while copying, you can specify the new file name in the destination.
Command:
Output:
This shows that file1.txt
was copied to /home/user/Documents/
and renamed as newfile.txt
.
Example 3: Copy Multiple Files to a Directory
To copy multiple files to the same directory, list each file before the target directory.
Command:
Output:
Each file is copied individually, and the output shows the source and destination paths.
Example 4: Recursive Copy of a Directory
To copy a directory and its contents, use the -r
(recursive) option.
Command:
Output:
This output shows that myfolder
and all its contents, including any subdirectories, are copied to /home/user/Backup/
.
Example 5: Interactive Mode
If you use the -i
(interactive) option, cp
will prompt before overwriting any existing files in the destination.
Command:
Output (if the file already exists in the destination):
Typing y
will confirm and allow the overwrite; typing n
will cancel the copy for that file.
Example 6: Preserve File Attributes
Using the -p
option preserves the original file permissions, timestamps, and ownership.
Command:
Output:
In this case, file1.txt
is copied to /home/user/Documents/
with its original attributes intact (though the output doesn’t explicitly show attribute preservation).
Example 7: Copy All Files of a Specific Type
You can copy all files of a specific type using a wildcard (*
).
Command:
Output:
Each .txt
file in the current directory is copied to /home/user/Documents/
.
These examples demonstrate how cp
can be used to copy files and directories, maintain original attributes, and interactively confirm overwrites.