The cp command is one of the most frequently used commands for copying files and directories from one location to another. Mastering cp is essential for daily operations, backups, and deploying application files in RHEL.
Example 1: Copy a file to a directory
# Copy the file 'main.c' into the 'src' directory
cp main.c src/
Explanation: This command takes the source file main.c from the current directory and creates an identical copy of it inside the src directory. The original file main.c remains unchanged.
Example 2: Copy a file and rename it
# Copy 'config.prod' to the current directory and name the copy 'config.dev'
cp /etc/config.prod ./config.dev
Explanation: When the destination is a new filename, cp creates a copy of the source file with that new name. This is useful for creating backups or different versions of a file.
Example 3: Copy multiple files to a directory
# Copy 'file1.txt' and 'file2.txt' into the 'backup' directory
cp file1.txt file2.txt backup/
Explanation: You can list multiple source files before the final destination directory. The cp command will copy each of the specified files into that directory.
Example 4: Copy with verbose output
# Copy 'large_file.iso' to the '/mnt/usb' directory and show the action being performed
cp -v large_file.iso /mnt/usb/
Explanation: The -v (verbose) option makes cp print a message indicating which file is being copied to which destination. This is helpful for tracking progress, especially when copying many files or large files.
Example 5: Interactive copy to prevent overwrites
# Copy 'document.txt', but prompt for confirmation before overwriting if it already exists
cp -i document.txt archives/
Explanation: The -i (interactive) option adds a layer of safety. If a file named document.txt already exists in the archives directory, cp will pause and ask for your confirmation (y/n) before proceeding with the overwrite.
Example 6: Preserve file attributes during copy
# Copy 'app.py' to 'app_backup.py' while preserving ownership, permissions, and timestamps
cp -p app.py app_backup.py
Explanation: The -p (preserve) option ensures that the new file has the same mode, ownership, and timestamps as the source file. This is crucial for backups or when permissions are critical.
Example 7: Copy only if the source is newer
# Copy 'index.html' to the '/var/www/html' directory only if the source is newer than the destination
cp -u index.html /var/www/html/
Explanation: The -u (update) option is very efficient for synchronizing directories. It will only perform the copy operation if the source file is newer than the destination file or if the destination file does not exist.