Copy & rename a file to the same directory without deleting the original file

Copy & rename a file to the same directory without deleting the original file

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Copy & Rename a File Without Deleting the Original

Developers frequently encounter scenarios where they need to generate derivative assets based on an existing source file. The most common pattern involves taking an original image and creating a thumbnail version while ensuring the high-resolution source remains untouched for future use or display. The core requirement is straightforward: create a duplicate of a file, change its name, and leave the original in place.

While this seems trivial at first glance, the implementation varies significantly depending on your environment and language stack. Whether you are scripting with Bash on Linux, using Node.js in an NPM project, or working within a PHP application, the fundamental logic remains consistent: read the source into memory (or stream it), write it to a new destination path, and handle any potential I/O errors gracefully.

The Logic Behind the Operation

The strategy relies on two distinct file system operations performed sequentially: copying and renaming. You must never attempt to rename the original file directly if your goal is to retain it; renaming is inherently an atomic operation that moves or overwrites the target. Instead, you perform a copy operation first. This creates a new file handle pointing to the same data as the source but with a unique path. Once the copy is successfully written to disk, you rename the new file to your desired identifier (e.g., one_thumb.jpg).

In most modern operating systems, these operations are atomic enough that partial failures are rare unless interrupted by an external force or disk failure. However, checking the return value of each system call or method is mandatory for robustness. If the copy fails due to insufficient permissions or disk full errors, you should not proceed to the rename step, nor should you attempt to clean up the original file unnecessarily.

Implementation in PHP

For those working with PHP, particularly within a web server context, the copy() function is the standard approach. It accepts two arguments: the source path and the destination path. You pass the original filename as the first argument and construct the new filename as the second.

$originalPath = 'images/folder/one.jpg';
$newPath = 'images/folder/one_thumb.jpg';

if (copy($originalPath, $newPath)) {
    echo "Thumbnail created successfully.";
} else {
    // Handle error: check file_exists on source, permissions, or disk space
    echo "Failed to copy the file.";
}

This approach is efficient because it leverages the operating system's underlying copy mechanism. It does not require loading the entire file into memory unless the copy function falls back to a stream-based implementation in older environments or specific configurations, though on modern PHP versions, copy() usually handles large files via streaming without excessive RAM usage. If you need more control over the process—such as validating the MIME type of the new file before renaming—you might consider using file_get_contents() and file_put_contents(), but that introduces memory overhead proportional to file size.

Implementation in Bash

If you are managing server-side tasks via a shell script, the command line tools offer a concise solution. The cp command copies files, and while it lacks a direct "rename" flag, you can chain commands or use shell variable substitution to achieve the result in one line.

# Copy the file and assign the new name immediately
cp "images/folder/one.jpg" "images/folder/one_thumb.jpg"

# Verify success before proceeding if this is part of a larger pipeline
if [ $? -eq 0 ]; then
    echo "Copy successful"
fi

Alternatively, you can use the mv command with a temporary variable to ensure the rename happens atomically after the copy completes. This pattern prevents scenarios where a script crashes between the copy and the rename, leaving orphaned files behind.

Performance Considerations

When dealing with high-volume image processing, such as generating thumbnails for thousands of uploads, performance becomes a critical factor. Copying a file is generally faster than reading it into memory and writing it back because the operating system can utilize disk caching and optimized block-level copying routines. However, if the source and destination paths are identical (which they are not in this case, but hypothetically), some systems might optimize the operation by skipping the copy entirely. Since we are changing the filename, the system must always write data to a new inode.

A potential pitfall occurs when the disk runs out of space during the copy operation. The original file will remain intact, but the new file will be incomplete or missing. Always check the return status of the copy function before attempting any further processing on the new file. In PHP, ensure you do not assume copy() always succeeds; in Bash, always inspect $?.

For enterprise applications requiring strict audit trails or zero-downtime updates during the copy process, consider using atomic rename patterns where a temporary file is created first, then moved to the final destination name once validation passes. This ensures that if the process fails partway through, no partial thumbnail is left in the directory structure.

Our network