0
0
Linux CLIscripting~5 mins

cp (copy files and directories) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Copying files or folders is a common task when you want to make a backup or move data without deleting the original. The cp command in Linux lets you do this quickly from the command line.
When you want to make a backup copy of a file before editing it.
When you need to duplicate a folder with all its contents to another location.
When you want to copy a file from one directory to another to organize your files.
When you want to copy multiple files at once into a new folder.
When you want to copy hidden files along with regular files in a directory.
Commands
This command copies the file named example.txt to a new file named backup.txt in the same directory. It is useful for making a quick backup of a file.
Terminal
cp example.txt backup.txt
Expected OutputExpected
No output (command runs silently)
This command copies the entire folder named myfolder and all its contents recursively into a new folder named myfolder_copy. The -r flag is needed to copy directories.
Terminal
cp -r myfolder myfolder_copy
Expected OutputExpected
No output (command runs silently)
-r - Copy directories and their contents recursively
This command copies file1.txt and file2.txt into the /home/user/documents/ directory. The -v flag shows each file being copied, so you see what is happening.
Terminal
cp -v file1.txt file2.txt /home/user/documents/
Expected OutputExpected
'file1.txt' -> '/home/user/documents/file1.txt' 'file2.txt' -> '/home/user/documents/file2.txt'
-v - Show details of files being copied
This command copies the folder myfolder to myfolder_backup preserving all file attributes like permissions and timestamps. The -a flag is for archive mode, which is useful for exact copies.
Terminal
cp -a myfolder/ myfolder_backup/
Expected OutputExpected
No output (command runs silently)
-a - Archive mode: copy directories recursively and preserve attributes
Key Concept

If you remember nothing else from cp, remember: use -r to copy folders and -v to see what is copied.

Common Mistakes
Trying to copy a folder without using the -r flag
cp will fail with an error because it does not copy directories by default.
Always add the -r flag when copying folders, like cp -r folder1 folder2.
Not specifying the destination directory correctly
Files may be copied with unexpected names or locations if the destination path is wrong.
Double-check the destination path and include a trailing slash for directories to avoid confusion.
Overwriting files without warning
cp will overwrite files silently, which can cause data loss.
Use the -i flag to ask before overwriting files, like cp -i file1 file2.
Summary
Use cp to copy files and folders from one place to another.
Add -r to copy directories and their contents recursively.
Use -v to see detailed output of what is being copied.