Linux CP Command
Usage of Linux cp Command:
This command is used to copy one or more files from source path to destination path.
cp –[OPTION] [source] [destination]
Example1 : Make a copy of file into same directory.
# cp originalfile newfile
- Creates a copy of “originalfile” in present working directory. The copied file will be named as “newfile”.
- Be very cautious while running the above command. If in case any file named as “newfile” exists in the same directory, it will be overwritten without confirmation prompt. This is the default behavior of cp command.
- If you want to be prompted while overwriting a file, use interactive option (i). For example : # cp –i originalfile newfile. If “newfile “ exists , you will be prompted as:
- cp : overwrite ‘newfile’?
- If you type any of the combination (y,Y,yes,YES), the newfile will be overwritten and if you type any of the combination (n,N,no,NO), the newfile will not be overwritten, i.e. command will be nullified.
Example2 :Copy a file named as originalfile to another location say (/home/root).
#cp originalfile /home/root
#cp originalfile /home/root/.
Both syntax are same. The forward slash-dot (/.) is implied in second command (the dot is very special in every Linux directory which means “this directory”).
Suppose originalfile is at following path: /home/root/folder1/contentfile. Then, above syntax will be written as:
# cp /home/root/folder1/contentfile/originalfile /home/root
Example3 : Copy a file named as originalfile to another location say (/home/root) with a new name testFile.
# cp originalfile /home/root/testFile
Example4 : Copy all files starting with word “testing” from home directory of user “root” to home directory of user “govind”.
# cp /home/root/testing* /home/ram
Note : Asterisk (*) is a wildcard or special character which expands to match other characters.
Example5 : Copy all files from the home directory of root to home directory of user ram.
# cp /home/root /home/ram
Example6 : See what cp command is doing.
# cp –v originalfile /home/root
Example7 : Create backup date of each copied file.
If destination folder already have a file and we know that by using cp command, it will overwrite the same in destination directory. So, we use – backup option , cp command will make a backup of each existing file.
# cp –backup=simple –v *.txt /home/root
–backup=simple option will create a backup file which will be marked by a tilde sign(~) at the end of file. —backup option has following control options:
- none, off: no backup will be created (even if –backup is given)
- number, t : make numbered backup
- existing, nil : numbered if numbered backup exist, simple otherwise.
- simple, never: always make simple backups.
Few questions with their answers are present in assignment section for this command.