cp (CoPy) command is quite flexible. There are a few ways it can be used to copy a file.
This can be used to copy the contents of a file (the source file) into a new file (the target file) with a new name:
cp <source_file.txt> <target_file.txt>
Exercise: Make a file called
file1.txt. Add some text to
file1.txt. Next, make
file2.txt like so…
$cp file1.txt file2.txt $ls $less file2.txt
You can think of this as basically shorthand for…
$cp ./file1.txt ./file2.txt
Once you make the connection that names, absolute paths, or relative paths can substitute in for <source_file.txt> or <target_file.txt>, you can see how you can place the copied file in some other directory, or pull a copy of a file from a source directory into your working directory.
Duplicating a file into a directory and renaming it:
cp <source_file.txt> <target/path/targetname.txt>
Duplicating a file from another directory into the current directory and renaming it:
cp <target/path/targetname.txt> <./targetname.txt>
Exercise: Make a directory called
dir1. Place a copy of
$mkdir dir1 $cp file1.txt dir1/file3.txt $ls $ls dir1
Quick Tip: Absolute paths as well as relative paths can be used as the source and target in
If you want to duplicate a file into a sub-directory, you don't need to change the name. To keep the name the same…
cp <source_file.txt> <target_directory>
Exercise: Try it out
$mkdir dir1 $cp file1.txt dir1 $ls $ls dir1
A list of files can also be copied in this way:
cp <source_file.txt> … <target_directory>
– where “…” means you can keep adding additional
source_files.txt, as many as you have.
Directories that contain files can also be duplicated using
cp. Just add the option
$mkdir dir1 $cp -R dir1 copy_of_dir1 $ls $ls copy_of_dir1
Exercise: I like to stay organized by adding notes to myself within directories. These text files that contain little notes to myself about the purpose for the directory. I call these README or ABOUT files.
lswill show you “01_Notes”, “02_Exercises”, etc)
ABOUT_this_class.txtwithin the course directory.
lessto browse your new file.
ABOUT_these_notes.txt. Double check that the content is the same.
Once you know cp, mv is pretty much the same thing with one exception. The source file will disappear once the operation is complete. This ends up renaming your file if you are working within the same directory. It acts like cut-and-paste instead of a copy-and-paste if you're moving between directories.
|mv <source_file.txt> <target_file.txt>||Rename source_file.txt to be called target_file.txt|
|mv <source_file.txt> <dir/target_file.txt>||Move source_file.txt into dir and rename it target_file.txt|
|mv <source_file.txt> … <dir>||Move source_file.txt(s) into dir and keep the names the same|
Exercise: Remember your directory called 160825_options_ex? MOVE that whole directory and its contents to the new directory
~/courseDirectory/02_Exercises you recently created within your course directory (where ~ stands for your appropriate path).