Bash Copy Command
Copy files and directories in Linux
📋 What is the CP Command?
The cp command (copy) duplicates files and directories from one location to another. It preserves the original file while creating an exact copy at the destination, making it essential for backups and file management tasks.
# Copy a file
cp source.txt destination.txt
Common Copy Operations
Copy Files
Duplicate single files
cp file.txt copy.txt
Copy Directories
Copy entire folders
cp -r folder/ backup/
Multiple Files
Copy many files at once
cp file1 file2 folder/
Safe Copy
Prevent overwriting files
cp -i file.txt dest.txt
🔹 Copy a Single File
The cp command's basic syntax copies individual files to new locations or creates duplicates with different names. For example, cp file1.txt file2.txt creates a copy, while cp file1.txt /backup/ copies to a directory. The original file remains unchanged, preserving its attributes and content. This fundamental operation is crucial for backups, version control, and file organization in daily system administration tasks.
# Copy file to same directory with new name
cp document.txt document_backup.txt
# Copy file to different directory
cp document.txt /home/user/backup/
# Copy and rename in different directory
cp document.txt /home/user/backup/doc_copy.txt
Result:
File copied successfully Original file: document.txt (still exists) New file: document_backup.txt (created)
🔹 Copy Multiple Files
Multiple files can be copied simultaneously by listing them before the destination directory. The final argument must specify a target directory, as in cp file1.txt file2.jpg /backup/. This approach saves time when organizing related files, creating backups, or transferring groups of documents. It's particularly useful for batch operations and automated scripts where efficiency is paramount.
# Copy multiple files to a directory
cp file1.txt file2.txt file3.txt /destination/
# Copy all text files
cp *.txt /backup/
# Copy specific file types
cp *.jpg *.png /images/
Result:
file1.txt copied to /destination/ file2.txt copied to /destination/ file3.txt copied to /destination/
🔹 Copy Directories
Copying entire directories requires the -r (recursive) option to include all contents and subdirectories. The command cp -r sourcedir/ destdir/ duplicates the complete folder structure, maintaining hierarchy and file relationships. This is essential for project backups, deployment processes, and migrating directory trees between locations while preserving organizational structure.
# Copy directory and all contents
cp -r source_folder/ destination_folder/
# Copy directory to existing location
cp -r project/ /home/user/backup/
# Copy hidden files too
cp -r folder/ backup/
Important Notes:
- Always use -r flag for directories
- Copies all files and subdirectories
- Preserves directory structure
- Creates destination if it doesn't exist
🔹 Interactive Copy (Safe Mode)
The -i (interactive) option enables safe copying by prompting before overwriting existing files. When a destination file already exists, cp -i asks for confirmation, preventing accidental data loss. This safety feature is invaluable when updating backups, synchronizing directories, or working in environments where file preservation is critical to system stability and data integrity.
# Prompt before overwriting
cp -i file.txt destination.txt
# Interactive copy of multiple files
cp -i *.txt /backup/
Output:
cp: overwrite 'destination.txt'? y (Type 'y' for yes, 'n' for no)
🔹 Preserve File Attributes
The SCP -p flag (lowercase, for preserve) retains the original modification times, access times, and file modes (permissions) of the transferred files. Using scp -p file.txt user@host:/tmp/ ensures the copied file's timestamp on the destination matches the source. This is important for archival purposes, for maintaining correct file order, or when the timestamps are meaningful for application logic (e.g., build artifacts, logs). Without this flag, the copied files receive new timestamps corresponding to the moment of transfer, which can be misleading.
# Preserve mode, ownership, and timestamps
cp -p original.txt copy.txt
# Preserve attributes when copying directory
cp -rp source_folder/ backup_folder/
Preserved Attributes:
- File permissions (read, write, execute)
- Ownership (user and group)
- Timestamps (creation and modification)
- Extended attributes
🔹 Useful CP Options
The cp command offers numerous options to handle various copying scenarios and requirements. Flags like -v (verbose) provide operation feedback, -u (update) copies only newer files, and -n (no-clobber) prevents overwrites. These options provide flexibility for tasks ranging from simple file duplication to complex backup operations with specific safety and logging requirements.
Common Options:
- -r : Copy directories recursively
- -i : Interactive mode (prompt before overwrite)
- -f : Force copy (overwrite without asking)
- -p : Preserve file attributes
- -v : Verbose (show what's being copied)
- -u : Update (copy only newer files)
# Verbose copy
cp -v file.txt backup.txt
# Force overwrite
cp -f source.txt destination.txt
# Update only newer files
cp -u *.txt /backup/
# Combine multiple options
cp -riv folder/ backup/
🔹 Practical Examples
Everyday uses of head include validating data files, monitoring log heads, and creating data samples. A data scientist might run head -1000 large_dataset.csv > sample.csv to create a manageable sample for testing scripts. A developer might use head -20 application.log to check recent activity after a deployment. These scenarios highlight head's role as a gatekeeper, providing a safe, controlled way to interact with the beginning of files and streams, which is often where the most current or defining information resides.
# Backup important files
cp -rp /home/user/documents/ /backup/documents_backup/
# Copy configuration file
cp /etc/config.conf /etc/config.conf.backup
# Duplicate project folder
cp -r myproject/ myproject_v2/
# Copy all images to new folder
cp *.jpg *.png /home/user/pictures/
# Create timestamped backup
cp file.txt file_$(date +%Y%m%d).txt