How to Create Multiple Files with the Same Base Name in Unix

How to Create Multiple Files with the Same Base Name in Unix

Photo of author
Written By Aaron Weiss

If you want to create multiple files with similar names (like abc.txt, abc.txt.1, abc.txt.2, etc.), there are a few approaches depending on your goal. Here’s a breakdown of the key concepts and how to do it.

1. Can You Automatically Version Files Like abc.txt.1, abc.txt.2, etc.?

Not by default. Most Linux/Unix file systems don’t support automatic versioning like this out-of-the-box.

To make this happen automatically for any program that creates abc.txt, you’d need a versioning file system—something that keeps older versions of files automatically. These exist but are not common in mainstream Linux distributions.

Alternative approach:
You can simulate this behavior with a script that checks if a file exists and then renames it with a unique identifier.

2. Option: Use a Bash Script with Timestamps or Process IDs

Here’s a basic way to handle this manually using a Bash script.

Script Logic:

# The script checks if the file already exists
if [ -f "$MY_FILE_NAME" ]; then
    # If it exists, rename it using the current process ID
    mv "$MY_FILE_NAME" "${MY_FILE_NAME}_$$"
    mv "$MY_NEW_FILE" .
else
    # Otherwise, just create or move the new file
    mv "$MY_NEW_FILE" .
fi

How it works:

  • $$ is the current process ID — so it guarantees a unique filename.
  • This prevents overwriting existing files.

You could also use a timestamp instead of a process ID to version your files.

3. Option: Create Multiple Numbered Files Quickly

If you just want to create a batch of similarly named files, you can use Bash expansion:

touch my_file{01..10}.txt

This creates:

my_file01.txt
my_file02.txt
...
my_file10.txt

Useful for quickly generating test files or looping over files in a script.

4. Want to Rotate Files Automatically?

For log-style rotation (e.g. file.log, file.log.1, file.log.2…), look into:

Logrotate

This tool helps you automatically rotate, compress, and rename log files based on size, time, or other rules.


Summary

TaskMethod
Automatically version files when overwrittenNot natively supported — use versioning file systems or scripts
Create files with different namesUse Bash expansion (touch my_file{01..10}.txt)
Avoid overwriting existing filesWrite a Bash script to rename old files using $PID or timestamps
Rotate logs or backupsUse logrotate

Aaron Weiss

Leave a Comment