Copy, Move & Remove
Copy
In Bash, cp
, mv
, and rm
are three fundamental commands for managing your files and directories. They allow you to copy, move (or rename), and remove items on your system.
Basic Usage
To make a copy of a file, specify the source file and then the destination file name for the copy.
Now, you will have two identical files: myfile.txt and backup.txt.
Copying a File to a Directory
You can also copy a file into an existing directory. In this case, the destination is the path to the directory. The copied file will retain its original name within that directory.
Example: To copy report.docx into the documents folder:
Or, to copy it into documents and give it a new name final_report.docx:
cp Options
-r
Copy directories recursively (including all files and subdirectories).-i
Interactive mode: Prompts before overwriting an existing file.-u
Update: Copy only if the source file is newer than the destination file, or if the destination file doesn't exist.-v
Verbose mode: Shows the name of each file as it's copied.
-r Copy Directories & Files Recursively
Example: Copy files to directory Copy multiple files to any directory.
Example: Copy directory to another directory
Move or Rename Files and Directories
The mv command is used for two main purposes: moving files/directories to a different location, or renaming files/directories.
Moving a File
To move a file, specify the source file and the destination directory.
Renaming Files and Directories
mv is also the command you use to rename a file or directory. You simply specify the current name as the source and the new name as the destination.
Similarly, to rename a directory:
mv Options
-i
Interactive mode: Prompts before overwriting an existing file/directory.-u
Update: Move only if the source file is newer than the destination file, or if the destination file doesn't exist.-v
Verbose mode: Shows the name of each file/directory as it's moved. Learn more aboutmv
Remove Files or Directories
The rm command is used to remove (delete) files or directories. Use rm
with caution, as deleted files are not moved to a "Recycle Bin" or "Trash" and can be difficult or impossible to recover!
Basic Usage: Removing a File
To delete a single file, simply use rm followed by the filename.
Remove Directories Recursively
You cannot remove an empty directory with rm
by default (you'd use rmdir
for that). To remove a directory that contains files or other subdirectories, you must use the -r
(recursive) option.
Force Delete
The -f
(force) option overrides any prompts or warnings. It will delete files even if they are write-protected, and it will not ask for confirmation. This option is dangerous if used carelessly, as it can lead to irreversible data loss.