# How I sort .env files without moving comments to the wrong place

A beginner-friendly guide to cleaning .env files, sorting keys, keeping comments attached, removing duplicates, and reviewing config changes safely.

- Date: 2026-09-27
- URL: https://ilham.dev/posts/how-to-sort-env-files-without-moving-comments-to-the-wrong-place/
- Markdown: https://ilham.dev/posts/how-to-sort-env-files-without-moving-comments-to-the-wrong-place/index.md
- Tags: env, configuration, devops, tools
- Reading time: 2 min


A messy `.env` file makes configuration harder to review. Sorting helps, but comments and duplicates need care.

The [.env Key Sorter](/tools/env-key-sorter/) tool gives me a safe place to test the idea before I put it into a script, server, or production workflow.

## The simple mental model

A messy `.env` file makes configuration harder to review. Sorting helps, but comments and duplicates need care.

I try to reduce the tool to one question: what input do I have, what output do I expect, and what would make the result unsafe or misleading?

## Step 1: Paste the 

Paste the .env content.

Start with a small example first. A small example is easier to inspect than a real production-sized case.

## Step 2: Keep comments attached to the key they explain

Keep comments attached to the key they explain.

## Step 3: Sort keys alphabetically

Sort keys alphabetically.

## Step 4: Decide what to do with duplicate keys

Decide what to do with duplicate keys.

## Step 5: Optionally align values for readability

Optionally align values for readability.

## Step 6: Review secrets before sharing output

Review secrets before sharing output.

## Step 7: Commit config examples, not real production secrets

Commit config examples, not real production secrets.

## My checklist

Before I trust the result, I check:

- Paste the .env content.
- Keep comments attached to the key they explain.
- Sort keys alphabetically.
- Decide what to do with duplicate keys.
- Optionally align values for readability.
- Review secrets before sharing output.
- Commit config examples, not real production secrets.

The tool saves time, but the important part is still understanding the input and reviewing the output before using it somewhere important.
