This chapter introduces the commands cp and mv used for duplicating and relocating files and directories, which are fundamental operations in file management.
1. Copying Files and Directories (cp)
The cp (copy) command is used to make a duplicate of a file or directory. The basic syntax requires a source and a destination.
$$cp \space [options] \space source \space destination$$
Execution Examples: Files
- Copy a file to the current directory (renaming it):Copy report.txt and rename the copy to report_backup.txt.
cp report.txt report_backup.txt - Copy a file to a different directory:Copy settings.conf from the current directory to the /etc/ directory.
cp settings.conf /etc/ - Copy multiple files to a directory:Copy file1.txt and file2.txt to the existing backups directory.
cp file1.txt file2.txt backups/
Copying Directories Recursively (-r)
To copy an entire directory and all of its contents (including subdirectories and files), you must use the -r (recursive) option.
Bash
cp -r assets new_assets_folder
2. Moving and Renaming (mv)
The mv (move) command has two primary functions, depending on the destination argument:
- Relocating (Moving): If the destination is an existing directory, the file or directory is moved into it.
- Renaming: If the destination is a new filename in the same directory, the file is renamed.
$$mv \space [options] \space source \space destination$$
Execution Examples: Renaming
To rename a file from old_name.txt to new_name.txt in the current location:
mv old_name.txt new_name.txt
Execution Examples: Moving
- Moving to a different directory:Move data.csv from the current directory to the archive directory.
mv data.csv archive/ - Moving and renaming simultaneously:Move data.csv to the archive directory and rename it to jan_data.csv.
mv data.csv archive/jan_data.csv - Moving an entire directory:Move the drafts directory into the documents directory. Note that the -r option is generally not needed for moving directories as mv handles them by default.
mv drafts documents/
3. Safely Overwriting
By default, both cp and mv will overwrite existing files without warning. To prevent accidental loss of data, you can use the interactive flag:
- Interactive Flag (
-i): Prompts the user for confirmation before overwriting an existing file.
cp -i file_a.txt /backup_folder/file_a.txt
