Skip to content

How to Set Up Environment Variables in Linux

DodaTech 1 min read

In this tutorial, you'll learn about How to Set Up Environment Variables in Linux. We cover key concepts, practical examples, and best practices.

The Problem

Your app needs database passwords, API keys, or configuration values that shouldn't be hard-coded. Environment variables solve this.

Quick Fix

1. Set a temporary variable

export DATABASE_URL="postgresql://user:pass@localhost:5432/mydb"

This variable is available in the current terminal session only. Close the terminal and it's gone.

2. Check it's set

echo $DATABASE_URL
env | grep DATABASE

3. Use it in a command

DATABASE_URL="postgresql://user:pass@localhost/mydb" python app.py

This sets the variable for that single command.

4. Set permanently (per user)

Add to ~/.bashrc or ~/.zshrc:

echo 'export DATABASE_URL="postgresql://user:pass@localhost:5432/mydb"' >> ~/.bashrc
source ~/.bashrc

5. Set permanently (system-wide)

echo 'export DATABASE_URL="postgresql://..."' | sudo tee /etc/profile.d/mydb.sh

6. For systemd services

[Service]
Environment=DATABASE_URL=postgresql://user:pass@localhost/mydb
EnvironmentFile=/etc/myapp/env.conf

Using .env Files

Create a .env file:

DATABASE_URL=postgresql://user:pass@localhost/mydb
API_KEY=sk-abc123
DEBUG=true

Load it from Python with python-dotenv or from bash with:

export $(grep -v '^#' .env | xargs)

Common Variables

Variable Purpose
PATH Where to find executables
HOME Current user's home directory
LANG System language/locale
NODE_ENV Node.js environment (production/development)
DATABASE_URL Database connection string

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro