fbpx Linux Environment Variables: env, export and Examples | Certificação Linux

Linux Environment Variables: env, export and the Most Important

📅 01/01/2019 ⏱ 6 min ✍️ Uira Ribeiro
Linuxcommands
Linux Environment Variables: env, export and the Most Important
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

Environment variables are key=value pairs that the operating system keeps in memory and makes available to all running processes. They control the behavior of the shell, programs, and scripts — from where the system looks for executables (PATH) to the language displayed in programs (LANG).

Understanding environment variables is essential for administering servers, writing robust scripts, and passing certifications like LPIC-1 (topic 105).

List environment variables

There are three commands to list variables, each with a different scope:

# env — lista apenas variáveis de ambiente exportadas
env

# printenv — igual ao env, mas pode filtrar por nome
printenv
printenv PATH          # mostra só a variável PATH
printenv HOME USER     # múltiplas variáveis de uma vez

# set — lista variáveis de ambiente + variáveis locais do shell + funções
set

The practical difference: env and printenv show only what child processes inherit. set shows everything, including temporary variables that exist only in the current shell session.

Most important environment variables

VariableContentExample
PATHDirectories where the shell looks for executables/usr/local/bin:/usr/bin:/bin
HOMECurrent user's home directory/home/joao
USERLogged-in usernamejoao
SHELLUser's default shell/bin/bash
LANGDefault language and encodingpt_BR.UTF-8
PWDCurrent working directory/var/www/html
OLDPWDPrevious directory (before last cd)/home/joao
EDITORSystem's default text editorvim
TERMTerminal type in usexterm-256color
PS1Shell prompt format\u@\h:\w\$
UIDUser's numeric ID1000
HOSTNAMEMachine's hostnameservidor01

Create and export variables

Local variable (exists only in current shell session)

# Cria variável local — processos filhos NÃO herdam
NOME="João"
echo $NOME          # João
bash -c 'echo $NOME' # (vazio — filho não herda)

Exported variable (child processes inherit)

# export torna a variável disponível para processos filhos
export NOME="João"
bash -c 'echo $NOME'  # João — filho herda!

# Criar e exportar em uma linha só
export DB_HOST="localhost"
export DB_PORT=5432

# Ver se uma variável está exportada
export -p | grep NOME

Variable for a single command (without affecting current environment)

# Passa a variável APENAS para aquele comando — não altera a sessão
LANG=en_US.UTF-8 man ls          # manual em inglês

# Muito útil para scripts e testes
NODE_ENV=production npm start
DEBUG=* node app.js
PYTHONDONTWRITEBYTECODE=1 python script.py

# Múltiplas variáveis antes do comando
LANG=en_US DB_HOST=prod ./meu_script.sh

The env command

List filtered variables

# Ver todas as variáveis de ambiente
env

# Filtrar por padrão
env | grep PATH
env | grep -i db   # busca case-insensitive

Run command with modified environment

# Sobrescrever PATH para um único comando
env PATH=/usr/local/bin:/usr/bin which python

# Adicionar variável sem afetar o shell atual
env MYSQL_HOST=db.prod.com ./backup.sh

Run with clean environment (-i)

The -i flag (or --ignore-environment) starts the command with a completely empty environment — useful for testing and to ensure no user environment variables affect execution:

# Roda bash com ambiente completamente limpo
env -i bash

# Roda script com apenas as variáveis necessárias
env -i HOME=/tmp PATH=/usr/bin:/bin ./script.sh

# Ver quantas variáveis existem normalmente vs. ambiente limpo
env | wc -l         # ~30–50 variáveis normalmente
env -i env | wc -l  # 0

Shebang with env in scripts

Using /usr/bin/env in the shebang instead of the interpreter's direct path makes the script more portable — env finds the interpreter in the system PATH, wherever it is installed:

#!/usr/bin/env python3
# Funciona em qualquer sistema onde python3 está no PATH

#!/usr/bin/env bash
# Melhor que #!/bin/bash em sistemas onde bash pode estar em outro local

#!/usr/bin/env node
# Comum em scripts Node.js

Permanent variables: where to define

Variables created in the terminal disappear when the session ends. To make them permanent, choose the right file according to the desired scope:

FileScopeWhen it is read
~/.bashrcCurrent userEach interactive (non-login) shell
~/.bash_profile or ~/.profileCurrent userLogin via terminal or SSH
/etc/environmentEntire systemAny user login (PAM)
/etc/profileEntire systemAny user login (login shell)
/etc/profile.d/*.shEntire systemAny user login
# Adicionar variável permanente para o usuário atual
echo 'export EDITOR=vim' >> ~/.bashrc
echo 'export JAVA_HOME=/usr/lib/jvm/java-17' >> ~/.bashrc
source ~/.bashrc   # Recarrega sem precisar fechar o terminal

# Adicionar ao PATH do usuário (sem sobrescrever o PATH existente)
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

# Variável para todos os usuários do sistema
echo 'EDITOR=vim' | sudo tee -a /etc/environment

# Verificar se foi aplicado após recarregar
source ~/.bashrc
echo $EDITOR

Manipulate PATH

The PATH is the most important system variable — it defines where the shell looks for executables. The order of directories matters: the shell uses the first executable it finds.

# Ver o PATH atual (separado por :)
echo $PATH
# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Adicionar diretório no início do PATH (maior prioridade)
export PATH="/opt/meu_programa/bin:$PATH"

# Adicionar no final (menor prioridade)
export PATH="$PATH:/opt/meu_programa/bin"

# Verificar qual executável o shell vai usar
which python3
type python3

# Ver todos os executáveis com aquele nome no PATH
type -a python

Remove variables

# unset remove a variável completamente
unset NOME
echo $NOME     # (vazio)

# Remover do export (mantém como local)
export -n NOME

Variables in scripts

#!/usr/bin/env bash

# Boas práticas em scripts
set -euo pipefail   # sai em erro, trata variáveis não definidas, propaga erros em pipes

# Ler variável de ambiente com valor padrão
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"

# Checar se variável obrigatória está definida
if [ -z "${API_KEY:-}" ]; then
    echo "ERRO: API_KEY não definida" >&2
    exit 1
fi

# Exibir variáveis definidas para debug
env | sort | grep "^DB_"

.env files and dotenv

Modern projects (Node.js, Python, Docker) use .env files to centralize configuration variables:

# Arquivo .env típico
DB_HOST=localhost
DB_PORT=5432
DB_NAME=meuapp
SECRET_KEY=chave-super-secreta

# Carregar no shell manualmente
export $(grep -v '^#' .env | xargs)

# Com Docker
docker run --env-file .env minha_imagem

# Com Docker Compose (lê .env automaticamente)
# Mas também pode definir explicitamente:
# env_file:
#   - .env

Quick reference

# Listar todas as variáveis exportadas
env | sort

# Criar variável local
VARIAVEL="valor"

# Exportar para processos filhos
export VARIAVEL="valor"

# Variável só para um comando
VAR=valor comando

# Ambiente limpo
env -i comando

# Remover variável
unset VARIAVEL

# Tornar permanente (usuário)
echo 'export VARIAVEL="valor"' >> ~/.bashrc && source ~/.bashrc

# Ver de onde vem um executável
which python3
type -a python3

# Adicionar ao PATH permanentemente
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp