Pipes and text

How to set environment variables in bash and zsh

Learn how to set environment variables in Bash and zsh with export, how to persist them in .bashrc or .zshrc, and the env prefix trick for the Fish shell.

8 minute lesson

~~~

An environment variable is a name/value pair inherited by child processes. In Bash and zsh, assign a shell variable and export it:

Setting them in the shell is the same:

export APP_ENV=development

Read it with printf or inspect the exported environment:

printf '%s\n' "$APP_ENV"
env | grep '^APP_ENV='

Typing $APP_ENV by itself tries to execute its value as a command. Variable expansion supplies text; it is not a print operation.

Limit a value to one process by prefixing the command:

APP_ENV=test node test.js

The current shell is unchanged after that command exits. This is ideal for one-off configuration.

To persist settings for future interactive shells, put them in the startup file your shell actually reads, commonly ~/.zshrc for zsh or ~/.bashrc for interactive Bash. Reload a known file with source ~/.zshrc, or open a new shell. Startup-file behavior differs between login and interactive shells, so diagnose with echo "$SHELL" and the shell’s documentation instead of editing every dotfile.

Environment variables are visible to the process and often to child processes and diagnostic tools. Do not treat them as encrypted storage. Avoid committing secrets to startup files or printing them in logs.

Remove a variable from the current shell with:

unset APP_ENV

Try it: export a value, read it from a child sh -c process, unset it, and confirm the next child no longer receives it.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →