How to Fix “Cp: Cannot Create Regular File ‘File’: File Exists”
Below are the solutions to resolve the “Cp: Cannot Create Regular File ‘File’: File Exists” problem in the Linux Operating System.
Solution 1: Use the -f option with cp
Using the -f option with the cp command in Linux forces the copy operation to overwrite the destination file if it already exists, resolving the “Cp: Cannot Create Regular File ‘File‘: File Exists” error. For example, cp -f gfg1.txt gfg2.txt will overwrite gfg2.txt with gfg1.txt without prompting or displaying an error message about the existing file.
Syntax:
cp -f source_file destination_file
Example:
cp -f gfg1.txt gfg2.txt
Output:
Solution 2: Remove the existing file before copying
This solution involves first forcibly removing the existing file using rm -f and then copying the source file to the destination. In the example rm -f gfg2.txt && cp gfg1.txt gfg2.txt, the -f flag with rm ensures that the file is removed even if it’s write-protected or doesn’t exist, followed by copying gfg1.txt to gfg2.txt.
Syntax:
rm -f destination_file && cp source_file destination_file
Example:
rm -f gfg2.txt && cp gfg1.txt gfg2.txt
Output:
Solution 3: Use the mv command to overwrite the existing file
The third solution uses the mv command to rename and overwrite the existing file. In the example mv gfg1.txt gfg2.txt, gfg1.txt is moved (renamed) to gfg2.txt, effectively overwriting gfg2.txt if it already exists. This approach directly replaces the destination file with the source file, resolving the “Cp: Cannot Create Regular File ‘File’: File Exists” error.
Syntax:
mv source_file destination_file
Example:
mv gfg1.txt gfg2.txt
Output:
How to Fix – Cp: Cannot Create Regular File ‘File’: File Exists
In Linux, while performing copying operations using the cp command, the error “Cp: Cannot Create Regular File ‘File’: File Exists” may occur when attempting to copy a file to a destination where a file with the same name already exists. This error is a safeguard to prevent accidental overwriting of files and potential data loss. To resolve this issue, several approaches can be used, such as using the -f option with cp to force overwrite, removing the existing file before copying, or using the mv command to rename and overwrite the existing file.