52 / 55 · 19 Linux & Command Line · Logs and Environment Variables← prev⊞ allnext →☰ Read as one page
7.4Environment Variables
Environment variables configure tests for different environments without changing code. They are the standard way to manage configuration across dev, staging, and production.
Setting Environment Variables
# Set for the current session
export BASE_URL=https://staging.example.com
export API_KEY=test-key-12345
export DB_HOST=localhost
export DB_PORT=5432
# Use in commands
curl -H "Authorization: Bearer $API_KEY" "$BASE_URL/api/users"
# Set for a single command only
BASE_URL=https://prod.example.com npx playwright test --project=smoke
Loading from .env Files
# .env file format
BASE_URL=https://staging.example.com
API_KEY=test-key-12345
DB_HOST=localhost
DB_PORT=5432
LOG_LEVEL=debug
# Load all variables from .env
export $(grep -v '^#' .env | xargs)
# Or load with a specific file
export $(grep -v '^#' .env.staging | xargs)
Default Values
# Use default if variable is not set
TIMEOUT=${TEST_TIMEOUT:-30000}
BROWSER=${TEST_BROWSER:-chromium}
WORKERS=${TEST_WORKERS:-4}
BASE_URL=${BASE_URL:-http://localhost:3000}
# Verify required variables are set
: "${API_KEY:?ERROR: API_KEY must be set}"
# If API_KEY is empty or unset, the script exits with the error message
Environment-Specific Configuration
# Pattern: different .env files per environment
# .env.dev
BASE_URL=http://localhost:3000
DB_HOST=localhost
# .env.staging
BASE_URL=https://staging.example.com
DB_HOST=staging-db.example.com
# .env.production
BASE_URL=https://www.example.com
DB_HOST=prod-db.example.com
# Load the right one
ENV=${ENVIRONMENT:-dev}
export $(grep -v '^#' ".env.${ENV}" | xargs)
echo "Running tests against $BASE_URL"
Viewing Environment Variables
# Show all environment variables
env
# Show all, sorted and filtered
env | sort | grep -i test
# Show a specific variable
echo $BASE_URL
# Check if a variable is set
if [ -z "$API_KEY" ]; then
echo "WARNING: API_KEY is not set"
fi