BASH

Set Project-Specific Environment Variables and Execute Commands

Manage different project environments by setting specific variables and executing commands within that context using a simple and effective bash script.

#!/bin/bash

# Usage: ./project-env.sh <command> [args...]
# Example: ./project-env.sh npm start
# Example: ./project-env.sh python app.py

# Define project-specific environment variables
export APP_ENV="development"
export DATABASE_URL="mysql://user:pass@localhost:3306/my_dev_db"
export API_KEY="dev-api-key-123"

# Optionally, load variables from a .env file
# if [ -f .env ]; then
#   export $(grep -v '^#' .env | xargs)
# fi

# Execute the command passed as arguments
if [ -z "$1" ]; then
  echo "Usage: $0 <command> [args...]"
  exit 1
fi

echo "Running command: $@ with project-specific environment..."
exec "$@"
How it works: This script provides a clean way to set project-specific environment variables and then execute any command within that modified environment. You can define your variables directly in the script or uncomment the section to load them from a `.env` file (which requires `grep` and `xargs`). The `exec "$@"` command replaces the current shell process with the specified command, ensuring that the environment variables are correctly inherited by the executed program. This is particularly useful for web developers working on multiple projects with different configurations or requiring specific API keys and database connections for local development.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs