export Command in Linux: Set and Export Shell Environment Variables
Learn export command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn export command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What export Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Mastering the export command in linux is essential for configuring runtime environments, defining search paths, passing secrets to application containers, and controlling process behavior across Linux systems. Implemented as a fundamental built-in command across all POSIX-compliant shells (including Bash, Zsh, Dash, and Ksh), export marks shell variables so that child processes inherit them automatically upon creation.
The export command in Linux marks shell variables or functions to be exported to the environment of subsequently executed child processes. Run export VAR='value' to define and export an environment variable, export PATH="/custom/bin:$PATH" to prepend a directory to your search path, or export -p to view all currently exported variables.
A fundamental concept in Unix process architecture is that shell variables are strictly local by default. When you declare DATABASE_URL='postgres://...' in a shell session, that variable exists only within the memory of the current shell process; external binaries and background child scripts spawned from that terminal cannot see it. Invoking export DATABASE_URL attaches the export attribute, propagating it to the process environment table.
Understanding how exported variables inherit across fork and exec boundaries, how to permanently persist variables in ~/.bashrc and /etc/profile.d/, and how to securely manage sensitive API tokens ensures your application deployments and administrative scripts execute deterministically.
What export Does and When to Use It
Under the hood, the Linux operating system represents process environments as a null-terminated array of pointers to null-terminated key-value strings (char **environ). When a shell spawns an external command, it invokes the fork(2) system call to clone the shell process and then calls execve(2) to load the executable. The third argument to execve(2) is the child's environment array.
When a variable is declared without export, the shell stores it in its internal symbol table and excludes it from the environment array passed to execve(2). When you run export, the shell sets an internal export flag on that symbol. When execve(2) is subsequently called, the shell iterates through all symbols carrying the export flag, serializes them into 'KEY=VALUE' strings, and passes them to the child process. Because Unix process memory is strictly isolated, a child process can read and modify its own environment copy, but can never alter the environment of its parent shell.
Under the hood, export gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -p, -n, -f, --help turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The export utility is packaged in bash across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether export is installed and inspect which binary path and version your shell resolves:
type -a export
export --version 2>/dev/null || man -f export
# Illustrative output (reviewed against documentation)
export is /usr/bin/export
export (bash)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y bash
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y bash
# Arch Linux
sudo pacman -S --noconfirm bash
# Alpine Linux
sudo apk add --no-cache bash
Command Syntax, Arguments, and Exit Status Codes
export [-fn] [NAME[=WORD]]... | export -p
The syntax is export [-fn] [NAME[=WORD]]... or export -p. In Bash and modern shells, you can assign and export simultaneously: export NAME=VALUE, or declare the variable first and export it later: NAME=VALUE; export NAME.
The -p option outputs all exported variables formatted in reusable shell syntax (e.g. declare -x VAR="value"). The -n option removes the export attribute from a variable without unsetting it, reverting it to a local shell variable. The -f option exports shell functions so they are available in subshells.
0— Successful completion; all variables or functions marked for export.1— Operational failure; invalid identifier name (e.g. containing hyphens or leading digits).2— Invalid command-line option supplied.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-p | -p | Display all exported variables in the current shell formatted as executable commands. |
-n | -n | Remove the export property from each NAME; the variable remains local to current shell. |
-f | -f | Treat each NAME as a shell function rather than a variable, exporting the function to subshells. |
--help | --help | Display shell built-in help documentation and exit. |
The export -p flag is invaluable for debugging environment drift. Running export -p | grep MY_ displays exactly which variables have active export attributes in the current shell session.
Using export -n provides a clean way to de-escalate sensitive variables. If a script requires a secret token for an internal shell operation but must spawn child utilities that should NOT see that token, running export -n SECRET_TOKEN strips the token from the child environment table while keeping it accessible within the script.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Set and Export an Environment Variable Simultaneously
Define a configuration variable and export it so child processes can access it.
export NODE_ENV="production"
python3 -c "import os; print(os.environ.get('NODE_ENV'))"
# Illustrative output (reviewed against documentation)
production
export assigns the value and sets the export bit, allowing Python to read NODE_ENV via os.environ.
2. Prepend a Directory to the System PATH Variable
Add a custom binary or local script folder to the beginning of the executable search path.
export PATH="/opt/custom/bin:$PATH"
echo $PATH | cut -d: -f1
# Illustrative output (reviewed against documentation)
/opt/custom/bin
Prepending ensures the shell searches /opt/custom/bin first before system directories.
3. List All Currently Exported Environment Variables with -p
Inspect active exported variables in the current shell environment.
export -p | head -n 4
# Illustrative output (reviewed against documentation)
declare -x HOME="/home/ubuntu"
declare -x LANG="en_US.UTF-8"
declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
declare -x USER="ubuntu"
export -p outputs each exported variable in declare -x syntax suitable for re-evaluation.
4. Remove the Export Attribute Using -n
Revert an exported variable back to a private local shell variable.
export SECRET_KEY="mysecret"
export -n SECRET_KEY
# Local variable still exists:
echo "Local: $SECRET_KEY"
# Child process cannot see it:
python3 -c "import os; print('Child:', os.environ.get('SECRET_KEY'))"
# Illustrative output (reviewed against documentation)
Local: mysecret
Child: None
The -n flag revokes the export attribute, hiding SECRET_KEY from subsequently spawned child processes.
5. Export a Shell Function to Subshells with -f
Make a custom shell function available inside bash subshell scripts.
my_tool() { echo "Deployed on $(hostname)"; }
export -f my_tool
bash -c "my_tool"
# Illustrative output (reviewed against documentation)
Deployed on prod-server-01
The -f option exports the function definition into the environment so invoked bash subshells can execute it.
6. Pass Environment Variables Temporarily to a Single Command
Set an environment variable strictly for the duration of a single command without polluting shell state.
APP_PORT=8080 ./start_server.sh
# Check if APP_PORT exists in parent shell:
echo "Parent APP_PORT: ${APP_PORT:-not set}"
# Illustrative output (reviewed against documentation)
Starting server on port 8080...
Parent APP_PORT: not set
Prefixing a command with VAR=VALUE exports the variable strictly to that child process without altering parent shell state.
Real-World Workflows, Pipelines, and Shell Automation
Application Deployment: Twelve-Factor Runtime Configuration
Configure Twelve-Factor app runtime settings from a secure deployment script using export.
#!/usr/bin/env bash
set -euo pipefail
echo "Configuring Twelve-Factor production runtime environment..."
# Export critical database and cache connection strings
export PORT="3000"
export NODE_ENV="production"
export DB_HOST="10.0.1.20"
export DB_PORT="5432"
export DATABASE_URL="postgresql://app_user:secret@$DB_HOST:$DB_PORT/app_db"
export REDIS_URL="redis://10.0.1.30:6379"
echo "Environment successfully exported. Starting application worker..."
exec node /var/www/app/server.js
# Illustrative output (reviewed against documentation)
Configuring Twelve-Factor production runtime environment...
Environment successfully exported. Starting application worker...
[Server] Listening on port 3000 in production mode.
Using export before exec node ensures the Node.js runtime inherits all configuration settings without hardcoding secrets in source code.
System-Wide Toolchain Configuration via /etc/profile.d/
Persist global toolchain environment paths and locale defaults for all system users.
#!/usr/bin/env bash
set -euo pipefail
echo "Provisioning global Go and Rust toolchain paths..."
cat << 'EOF' | sudo tee /etc/profile.d/dev-toolchain.sh > /dev/null
# System-wide Go and Rust toolchain path configuration
export GOROOT="/usr/local/go"
export GOPATH="$HOME/go"
export CARGO_HOME="$HOME/.cargo"
export PATH="$GOROOT/bin:$GOPATH/bin:$CARGO_HOME/bin:$PATH"
EOF
sudo chmod 644 /etc/profile.d/dev-toolchain.sh
echo "[SUCCESS] Global toolchain paths configured for all login shells."
# Illustrative output (reviewed against documentation)
Provisioning global Go and Rust toolchain paths...
[SUCCESS] Global toolchain paths configured for all login shells.
Scripts placed in /etc/profile.d/*.sh are automatically evaluated by all login shells upon SSH authentication.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding export inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Be extremely careful when exporting the PATH variable. Running export PATH="/custom/bin" without appending :$PATH wipes out access to standard system binaries like ls, sudo, and rm, requiring an absolute path (/usr/bin/export) to recover.
Exported environment variables are visible to all child processes spawned by your user account. In Linux, any process running under your UID can inspect the environment variables of any of your other processes by reading /proc/$PID/environ. Never export sensitive master credentials in long-lived multi-user shared sessions.
When invoking commands via sudo, the /etc/sudoers policy typically enables env_reset by default, stripping all exported user variables for security reasons. To pass specific environment variables through sudo, use sudo -E or configure Defaults env_keep += "MY_VAR" in /etc/sudoers.d/.
GNU/Linux, BSD, and BusyBox Implementation Differences
The export command is standardized in POSIX.1-2017. However, the syntax export VAR=VALUE (simultaneous assignment and export) was originally a Bourne-Again/Korn shell extension; older traditional Bourne shells required two commands: VAR=VALUE; export VAR.
Today, all modern shells—including Bash, Zsh, Dash (Ubuntu /bin/sh), and BusyBox sh—support export VAR=VALUE. However, export -f (exporting functions) is a GNU Bash extension and will fail in Dash or BusyBox.
Troubleshooting Common Errors and Diagnostics
export: 'MY-VAR': not a valid identifier
Root Cause: The variable name contains hyphens or characters not permitted in shell identifiers. Variable names can only contain alphanumeric characters and underscores, and must not start with a digit.
Resolution: Replace hyphens with underscores in variable names.
# Incorrect:
# export MY-VAR="value"
# Correct:
export MY_VAR="value"
Exported variable disappears after opening a new terminal session
Root Cause: The variable was exported only within the memory of the current terminal shell session. When that session closes, its memory is discarded.
Resolution: Add the export command to ~/.bashrc or ~/.profile to persist it across sessions.
echo 'export MY_VAR="value"' >> ~/.bashrc
source ~/.bashrc
sudo command fails to see exported variable
Root Cause: sudo enforces an env_reset security policy that scrubs user environment variables before launching the target command.
Resolution: Pass the -E (--preserve-env) flag to sudo or pass the variable inline.
sudo -E my_script.sh
# Or pass inline:
sudo MY_VAR="$MY_VAR" my_script.sh
Alternatives, Related Commands, and Related Tutorials
- type Command in Linux: Determine Command Interpretation and Path — Practical syntax, flags, and examples for
type. - Bash Pattern Matching: Globbing, Extended Globs, and Regex =~ Guide — Practical syntax, flags, and examples for
bash. - Grep Command in Linux: Search Text, Files, and Directories — Practical syntax, flags, and examples for
grep. - awk Command in Linux: Syntax, Text Patterns, and Field Processing — Practical syntax, flags, and examples for
awk. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
source script.sh or . script.sh.export VAR='value' to ~/.bashrc (for interactive shells) or ~/.profile (for login shells). For all system users, add it to a script inside /etc/profile.d/custom.sh.unset built-in: unset VAR_NAME completely destroys the variable. To remove the export attribute while keeping the variable local to the shell, use export -n VAR_NAME.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!