Library › Software development

Free guide

Environment Variables and .env

Environment variables let your application use configuration and secrets without putting them directly in your code.

1 min readFor developers

Beginner Cheatsheet

Environment variables let your application use configuration and secrets without putting them directly in your code.


1. What is an Environment Variable?

A variable stored outside your application code.

DATABASE_HOST=localhost
DATABASE_USER=root
DATABASE_PASSWORD=secret

Your application reads these values when it runs.


2. View a Variable

echo $PATH

Or:

echo $DATABASE_HOST

See many environment variables:

env

3. Set a Variable

For the current terminal session:

export APP_ENV=development

Check it:

echo $APP_ENV

⚠️ This usually disappears when you close the terminal.


4. The .env File

A .env file stores variables in a simple format:

APP_ENV=development
DATABASE_HOST=localhost
DATABASE_USER=root
DATABASE_PASSWORD=secret
API_KEY=abc123

Usually placed in your project's root:

my-project/
├── .env
├── src/
├── README.md
└── ...

5. .env ≠ Automatic

Creating .env does not automatically make every application read it.

Your framework, language, or library needs to load the file.

For example, many applications use:

.env → application → environment variables

6. Never Commit Secrets

Your .env may contain:

  • Database passwords
  • API keys
  • Tokens
  • Private credentials

So normally add it to .gitignore:

.env

Then Git won't track it.

Check:

git status

7. Use a .env.example

Instead of sharing your real .env, create:

.env.example

Example:

APP_ENV=development
DATABASE_HOST=
DATABASE_USER=
DATABASE_PASSWORD=
API_KEY=

This shows other developers what variables they need without exposing your secrets.


8. Common Pattern

Your code should use:

Environment variable
        ↓
Application
        ↓
Database / API / Service

Rather than:

Password written directly in code ❌

Essential Commands

TaskCommand
View variableecho $NAME
Set variableexport NAME=value
View environmentenv
Ignore .envAdd .env to .gitignore

Golden Rule

Configuration belongs outside your code. Secrets should never be committed to Git.