Command-Line (CLI) Reference

godotenv can be used as a command-line tool to run a process with environment variables loaded from a .env file. This is useful for executing scripts or applications in a controlled environment without polluting your shell's global environment.

Make sure you have installed the tool first. See the Installation Guide.

Usage

The basic syntax is:

godotenv [FLAGS] COMMAND [ARGS...]

godotenv will load the environment variables and then execute the specified COMMAND with its ARGS.

Flags

  • -f ENV_FILE_PATHS Specifies a comma-separated list of paths to .env files. If this flag is not provided, godotenv defaults to loading the .env file in the current working directory.

  • -o Stands for "overload". If this flag is present, variables from the .env files will override any environment variables that are already set in your shell. Without this flag, existing variables are preserved.

  • -h Displays a help message with usage instructions.

Examples

Basic Execution

Imagine you have a script.sh that relies on variables defined in ./.env.

File: ./.env

MESSAGE="Hello from .env"

File: ./script.sh

#!/bin/bash
echo "The message is: $MESSAGE"

You can run the script using godotenv:

godotenv ./script.sh

Output:

The message is: Hello from .env

Specifying a Custom .env File

If your environment file is located elsewhere, use the -f flag.

godotenv -f /path/to/my/config.env ./script.sh

Loading Multiple Files

You can load multiple files by providing a comma-separated list. They are loaded in order, and the first value found for a given key is used.

godotenv -f .env.defaults,.env.secrets ./my-app --port 8080

Overriding Existing Variables

Suppose you have a variable already set in your shell:

export MESSAGE="Hello from shell"

Running godotenv without -o will not change it:

$ godotenv ./script.sh
> The message is: Hello from shell

Using the -o flag forces the .env value to be used:

$ godotenv -o ./script.sh
> The message is: Hello from .env