Skip to content

Mojo Environment Variables

Environment variables are named text values that every program inherits from the shell that started it: HOME, PATH, LANG and any you set yourself. They’re a common way to pass settings such as a port number, a log level or an API key without changing code or adding command-line arguments. Mojo reads them with getenv() from std.os.

Checked with Mojo 1.2 on Linux. The programs below print Output: for a run with none of their variables set; runs with variables set show the command under “You’ll see”.

On Linux and macOS there are two ways to give a program an environment variable:

Terminal window
# for one command only: put it in front
APP_NAME=Ada mojo run greet.mojo
# for every command in this terminal from now on
export APP_NAME=Ada
mojo run greet.mojo

The first form is handy for trying things out, because it doesn’t stick around. By convention, names are in UPPER_CASE, and giving your own variables a prefix like APP_ keeps them apart from the system’s.

from std.os import getenv
def main():
var greeting = getenv("APP_GREETING", "Hello")
var name = getenv("APP_NAME", "friend")
print(t"{greeting}, {name}!")

Output:

Hello, friend!

getenv(name, default) returns the variable’s value as a String, or the default if the variable isn’t set. Neither is set here, so both defaults are used. Now set them:

Terminal window
APP_GREETING=Hola APP_NAME=Ada mojo run greet.mojo

You’ll see:

Hola, Ada!

Without a second argument, the default is an empty string. getenv never raises, so main doesn’t need raises. In Python you’d write os.environ.get("APP_NAME", "friend"); Mojo has the function but no os.environ dictionary.

Environment variables are always text, so convert them like any other text. Int() raises on bad input, so catch it and keep a sensible default. For on/off switches, compare the text yourself:

from std.os import getenv
def env_flag(name: String) -> Bool:
var value = getenv(name).lower()
return value == "1" or value == "true" or value == "yes"
def main():
var port = 8080
try:
port = Int(getenv("APP_PORT", "8080"))
except:
print("APP_PORT must be a number; using 8080")
var debug = env_flag("APP_DEBUG")
print("port:", port)
print("debug:", debug)

Output:

port: 8080
debug: False
Terminal window
APP_PORT=9000 APP_DEBUG=YES mojo run config.mojo
APP_PORT=abc mojo run config.mojo

You’ll see:

port: 9000
debug: True
APP_PORT must be a number; using 8080
port: 8080
debug: False

.lower() lets YES, Yes and yes all count. Bad input doesn’t crash the program; it falls back to the default and says so.

Environment variables are read every time the program starts, not when it’s built. One build serves every setting:

Terminal window
mojo build greet.mojo -o greet
./greet
APP_NAME=Linus ./greet

You’ll see:

Hello, friend!
Hello, Linus!

That’s the difference from -D defines, which are baked in when you compile (see Mojo Feature Toggles). Use -D for choices that should change the compiled code, such as turning debug checks on, and environment variables for settings that change between machines or runs, such as a port, a folder or a key.

Setting and removing variables in your program

Section titled “Setting and removing variables in your program”

setenv() and unsetenv() change the environment of the running program (and of anything it starts later). They don’t change the shell you ran it from:

from std.os import getenv, setenv, unsetenv
def main():
print(setenv("APP_MODE", "test"))
print(getenv("APP_MODE"))
print(setenv("APP_MODE", "live", overwrite=False))
print(getenv("APP_MODE"))
print(unsetenv("APP_MODE"))
print(getenv("APP_MODE", "(not set)"))
print(setenv("BAD=NAME", "x"))

Output:

True
test
True
test
True
(not set)
False
  • setenv(name, value) sets or replaces a variable and returns True.
  • With overwrite=False, an existing value is kept. Notice it still returned True here, even though APP_MODE stayed test. The setenv reference says it returns False only for an empty name or a name containing =, which is the last line. So don’t use the result to find out whether the value changed; call getenv again.
  • unsetenv(name) removes the variable, so getenv falls back to the default.
Task Python Mojo
Read with a default os.environ.get("X", "d") getenv("X", "d")
Read, missing is an error os.environ["X"] no direct version: check getenv("X") == ""
Set os.environ["X"] = "v" setenv("X", "v")
Remove del os.environ["X"] unsetenv("X")
List all variables os.environ not in the standard library

The getenv docs also note that these functions only work on macOS and Linux, which are the systems Mojo runs on.

Read APP_LANG (default en) and print Hello, Hola or Hallo for en, es or de. For anything else, print Sorry, no greeting for '<lang>' yet. Hello!.

Hint: an if / elif chain comparing the string is all you need.

Show solution
from std.os import getenv
def main():
var lang = getenv("APP_LANG", "en")
if lang == "es":
print("Hola")
elif lang == "de":
print("Hallo")
elif lang == "en":
print("Hello")
else:
print(t"Sorry, no greeting for '{lang}' yet. Hello!")

Output:

Hello

With APP_LANG=de mojo run lang.mojo it prints Hallo, and with APP_LANG=fr it prints Sorry, no greeting for 'fr' yet. Hello!.

Many projects keep local settings in a .env file with KEY=VALUE lines. Write load_env_file(path) that reads such a file, skips empty lines, lines starting with # and lines without =, and sets each variable without overwriting ones that are already set. Test it with a file you write in main.

Hint: text.split("=", 1) splits only at the first =, so values may contain = too. setenv wants Strings, so wrap the stripped parts in String().

Show solution
from std.os import getenv, setenv, remove
from std.pathlib import Path
def load_env_file(path: Path) raises -> Int:
var count = 0
for line in path.read_text().splitlines():
var text = line.strip()
if text == "" or text.startswith("#"):
continue
var parts = text.split("=", 1)
if len(parts) != 2:
continue
if setenv(String(parts[0].strip()), String(parts[1].strip()), overwrite=False):
count += 1
return count
def main() raises:
var path = Path(".env")
path.write_text("# settings for local runs\nAPP_NAME = Ada\nAPP_PORT=9000\n\nnot a setting\n")
print("settings found:", load_env_file(path))
print(getenv("APP_NAME"), getenv("APP_PORT"))
remove(path)

Output:

settings found: 2
Ada 9000

With overwrite=False, a real environment variable wins: APP_NAME=Grace mojo run dotenv.mojo prints Grace 9000. That’s the usual rule for .env files. Keep .env out of version control if it holds secrets.

  • getenv(name, default) from std.os returns the value as a String, or the default when the variable doesn’t exist. It never raises.
  • An empty variable is returned as "", not as the default.
  • Values are text: use Int() in try for numbers, and compare strings for on/off switches (Bool("no") is True).
  • Built programs read the environment when they start; -D defines are fixed when you compile.
  • setenv / unsetenv change the running program’s environment, not your shell’s; overwrite=False keeps an existing value but still returns True.

Next up: Mojo building & compilation targets, turning your code into programs for your machine and others.

Quick check

1. APP_LEVEL is not set. What does getenv("APP_LEVEL", "info") return?
2. You run APP_DEBUG=no mojo run app.mojo, and the code uses Bool(getenv("APP_DEBUG")). What do you get?
3. Your program calls setenv("APP_MODE", "test"). What happens in the terminal you ran it from?
4. You want to change a server port without rebuilding the program. What fits best?