Untitled Document
cp Command

The cp command stands for copy . It is used for copying a file or group of files .It creates an exact image of the file on disk with different name . The cp command requires at least two filenames to be specified in the command line .

1. Basic Example -

Run below cp command it will first create destination file if it doesn't exist before copying takes place . If not, It simply be overwritten without any warning from the system .So be careful when you choose your destination filename .

   cp emp.csv emp1.csv   

2. Copying file into other directory

Below command copies the file emp.csv from current directory to directory - user .

   cp emp.csv progs/user

3. Copying file into other directory - with shorthand notation (.) dot

For instance , to copy the file .profile from /home/mangesh to you current directory , you can use either two commands ..

   cp /home/mangesh/.profile .profile  --------- Destination is a file ( and you are at you current directory )
   cp /home/mangesh/.profile .         --------- Destination is current directory 

4. Copying Multiple files in single invocation

cp can also be used to copy more than one file in single stroke , In that case the destination ( last filename ) must be a directory . For belwo command to work , the progs directory must exist because cp won't create it .

   cp odd_even.ksh user_monitor.ksh case.kash shell_progs  --------- copies all three files in shell_progs directory .

5. Copying files having similar pattern .

Suppose if you want to copy all the .txt ( text files ) from current directory to some other , then we can use UNIX /Linux special metacharacter * to the cp command . Run below command to perform this action

   cp *.txt* shell_progs/logs  
   cp samp*  shell_progs/logs  ---------------- Copies all file begining with samp to shell_progs/logs directory 

6. Copying files interactively ( -i ) option .

The -i (interactive) options warns the user before overwritting the destination files .If logs.txt exists , cp prompts for a response . A y at this prompt overwrites the file , any other response leave it uncopied .

   cp -i user.txt logs.txt
   cp: overwrite logs.txt (yes/no) ? y 

7. Copying Directories Structures ( -R ) option .

The cp -R (Recursive) options copy an entire directory structure i.e it copies all the sub-direcories and files it host .Below command copies all the directories shell_progs, logs, output from my_progs to user_progs

   cp -R my_progs user_progs
Attention ! How cp behaves here depends upon whether user_progs also exists as a directory . If user_progs doesn't exist , cp creates it along with the associated subdirectories . But if user_progs exists , my_progs becomes a sub-directory under user_progs . This means that vthe command run twice in succession will produce different results !
Untitled Document