The cp command in Linux is used to copy files and directories.
$cp [OPTION]... SOURCE...Directory
The SOURCE here means all the files that you want to copy and the last argument must be a Directory where you want to copy the files
$cp notes.txt D1
will copy the file notes.txt to directory D1.
$cp notes.txt read.c write.c /home/baljit/D2
will copy the files notes.txt, read.c and write.c to directory D2 which is inside /home/baljit directory.
Note: You can copy multiple files at the same time to a Directory but you can not copy single file to multiple Directories at the same time.
-a: option not only copies data but also the file attributes. By default the timestamp (in the destination directory) changes to current time when you copy a file. But with -a option it remains the same. For example
Check the timestamp of file f1 before copying. Then it is copied to directory Copy2 using -a option. Now, the file f1 in directory Copy2 also has the same timestamp.
-b: option creates a backup file in the destination directory. This happens only if a file with the same name is already in the destination directory. One can identify the backup file with the tilde(~) symbol.
-i: option gives a prompt in case a file with the same name already exists in the destination directory. For example:
Since, f1 already exists in D2, so when we use cp with -i option to copy file f1 again into D2 the system prompts a message to confirm the overwrite. Now if you are sure you want to overwrite then press ‘y’ else ‘n’ and then ‘enter’ key.
-l: option hard-links the files rather than creating a separate copy in the destination directory. The advantage here is when you update any one of them, the other one automatically gets updated with the same content. To practice it, suppose you want to copy file f1 (which is in your current directory) to any directory you want (suppose D1) write
$cp -l f1 D1
This creates a link of f1 inside directory D1. The link name is same as filename.
-n: option prevents cp from overwriting a file in the destination directory if a file with the same name already exists.
-r / -R: option is used to copy directories. It recursively copies the entire content of the source directory to the destination directory. For example
$cp -r D1 D2
will copy the directory D1 (along with its contents) to directory D2.
-s: this option creates symbolic links rather than hard links (as with -l option)
-t: option helps to change the order of Source and Destination. For example:
we specify the destination directory D1 before the source file f3.
Q1. Copy a file f1 into directory D1 but the name after copying must be changed to new_f1
Q2. As an admin you want to copy a file f1 (created by a different user) into directory D1. Make sure that after copying the ownership of f1 inside D1 does not change.