cp / mv / rm
cp copies files or directories, mv moves or renames them, and rm deletes them. These are the fundamental commands for file management.
Syntax
cp [options] source destination mv [options] source destination rm [options] file...
Options
| Command / Option | Description |
|---|---|
| cp file destination | Copies a file to the specified location. |
| cp -r directory destination | Copies a directory recursively. |
| cp -p file destination | Copies a file while preserving its permissions, timestamps, and other attributes. |
| cp -i file destination | Prompts for confirmation before overwriting an existing file. |
| cp -u file destination | Copies only when the source file is newer than the destination. |
| mv file destination | Moves a file to the destination. If the destination is in the same directory, the file is renamed. |
| mv -i file destination | Prompts for confirmation before overwriting an existing file. |
| rm file | Deletes a file. |
| rm -r directory | Deletes a directory recursively. |
| rm -f file | Force-deletes without prompting. Does not produce an error if the file does not exist. |
| rm -rf directory | Force-deletes a directory and all its contents recursively. This cannot be undone — use with extreme caution. |
| rm -i file | Prompts for confirmation before deleting each file. |
Sample Code
The following examples use this directory structure.
Copy a file.
cp file.txt backup.txt ls archives backup.txt file.txt src
Copy an entire directory. The -r option is required.
cp -r src/ src_backup/ ls archives backup.txt file.txt src src_backup
Copy a directory while preserving its attributes (useful for backups).
cp -rp src/ backup/
Move a file to another directory.
mv file.txt archives/ ls archives backup.txt src src_backup
Rename a file (moving within the same directory).
mv backup.txt old_backup.txt ls archives old_backup.txt src src_backup
Delete a file.
rm old_backup.txt ls archives src src_backup
Delete all files matching a wildcard pattern.
rm *.log
Force-delete a directory and all its contents.
rm -rf src_backup/ ls archives src
Notes
'$ rm -rf' deletes an entire directory without any confirmation, so specifying the wrong path can cause serious data loss. When using a variable in the path (e.g., '$ rm -rf $DIR/'), wrap the variable in double quotes ('"$DIR"') or verify it is not empty before running the command — otherwise an empty variable could expand to '$ rm -rf /'.
To inspect file details, see ls.
If you find any errors or copyright issues, please contact us.