Basic Operations
Bash
# Set (current session only)
export MY_VAR="hello"
export PORT=3000
# Inspect
echo $MY_VAR
printenv MY_VAR
# List all environment variables
env
printenv
export -p
# Unset
unset MY_VAR
# Default if the variable is unset
echo ${MY_VAR:-"default"}
# Check whether the variable exists
[[ -z "$MY_VAR" ]] && echo "unset" || echo "set"Persistence — File Locations
| File | Scope | When it runs |
|---|---|---|
/etc/environment | System-wide | At login |
/etc/profile | System-wide | Login shell |
/etc/profile.d/*.sh | System-wide | Login shell |
~/.profile | Current user | Login shell |
~/.bashrc | Current user | Interactive bash |
~/.zshrc | Current user | Interactive zsh |
Bash
# Add to ~/.bashrc or ~/.zshrc
export PATH="$HOME/.local/bin:$PATH"
export JAVA_HOME="/usr/lib/jvm/java-21-openjdk-amd64"
export EDITOR="vim"
# Apply
source ~/.bashrc
# or
. ~/.zshrcManaging PATH
Bash
# Add a directory to PATH
export PATH="$HOME/bin:$PATH" # prepend (higher priority)
export PATH="$PATH:/opt/custom/bin" # append
# Show current PATH
echo $PATH | tr ':' '\n'
# Locate a command
which python3
type -a python3 # show all locationsPass Variables to a Single Command
Bash
# Prefixing applies only to that command
NODE_ENV=production PORT=8080 node server.js
# Same thing via env
env NODE_ENV=production PORT=8080 node server.js
# Run with a clean environment
env -i PATH=$PATH node server.jsManaging .env Files
Bash
# Example .env file
DB_HOST=localhost
DB_PORT=5432
DB_USER=app
DB_PASS=secret
NODE_ENV=development
# Load a .env file (bash)
set -a; source .env; set +a
# Load only variable assignments
export $(grep -v '^#' .env | xargs)
# Apply .env to the current session
while IFS= read -r line; do
[[ "$line" =~ ^[^#] ]] && export "$line"
done < .envNote: Always add .env files to .gitignore.
Environment Variables in System Services (systemd)
INI
# /etc/systemd/system/myapp.service
[Service]
Environment=NODE_ENV=production
Environment=PORT=3000
EnvironmentFile=/etc/myapp/.env # load from a fileBash
systemctl daemon-reload
systemctl restart myapp
# Verify
systemctl show myapp --property=EnvironmentEditorial note
AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us
Topic-related official docs (auto-linked · not per-claim sources)Linux man pages ↗
Questions & answers
Ask a question about this guide. We'll review and reply.