How to Use the Export Command in Linux

The Linux export command is a built-in shell command that marks variables and functions for inheritance by child processes. Without export, a variable created in the current shell remains local to that shell and cannot be accessed by scripts or subprocesses launched from it. After the variable is exported, it becomes an environment variable that child processes can read and use.

This guide explains how the export command works, covers its available options with practical examples, shows how to preserve exported variables between sessions, compares export with related commands, and explains how to resolve common problems.

Key Takeaways

  • The export command turns a shell variable into an environment variable that child processes can access.
  • A variable created without export remains a shell variable and is not visible to scripts or subprocesses.
  • Use export -p to display exported variables, export -n to remove a variable from the export list without deleting it, and export -f to export shell functions.
  • Variables exported in a terminal are removed when the session closes. To preserve them, place the relevant statement in ~/.bashrc, ~/.bash_profile, or /etc/environment.
  • When changing PATH, append a directory with export PATH="$PATH:/new/directory" instead of replacing the existing value.
  • export follows the POSIX standard and works across compatible shells. declare -x is specific to Bash but supports additional attributes. Use env VAR=value command when a variable should apply to only one command.
  • Neither sudo nor cron normally inherits the complete environment of your interactive shell. Variables must be passed explicitly or defined in the appropriate configuration.

What Is the Export Command in Linux?

The export command is a POSIX-standard shell built-in supported by compatible shells such as Bash, sh, and dash. Other shells, including Zsh, also implement it for compatibility. Its main purpose is to mark a shell variable as an environment variable so that child processes inherit it.

To understand why this is important, it helps to distinguish between shell variables and environment variables.

Shell Variables vs. Environment Variables

When you open a terminal and create a variable like this:

You create a shell variable. It exists only in the current shell session. The variable will not automatically be available in a new terminal tab, a script, or a subprocess.

An environment variable is part of a process environment. This environment consists of key-value pairs supplied to a process when it starts. When the shell starts a child process, that process receives a copy of the shell environment. Frequently used environment variables include PATH, HOME, and USER.

Note: Shell variable assignments must not include spaces around the equals = sign.

MY_VAR=value    # Correct
MY_VAR = value  # Incorrect

The export command connects these two variable types. It adds a shell variable to the process environment so that child processes created by the current shell receive it.

How Export Makes Variables Available to Child Processes

The following example demonstrates why export is required. First, create a variable and start another Bash process that attempts to display it:

# Without export
MY_VAR="example-value"
bash -c 'echo $MY_VAR'

The command displays nothing because MY_VAR was not added to the environment. Compare it with the exported version:

# With export
export MY_VAR="example-value"
bash -c 'echo $MY_VAR'

Output

The child Bash process can access the variable because it received the variable as part of its inherited environment.

Environment inheritance works in only one direction. A child process receives a copy of its parent process environment, but changes made inside the child process are not sent back to the parent. If a script changes MY_VAR, the value in the current shell remains unchanged.

Basic Syntax of the Export Command

The general export syntax is:

export [options] [NAME[=VALUE] ...]

You can export an existing variable or create and export a variable with a single command.

Export Syntax Components

Component Description
export The built-in shell command.
NAME The name of the variable or function being exported.
=VALUE An optional value assigned while the variable is exported.
options Flags that change the command behavior, including -p, -n, and -f.

Export Command Options

The export command supports three primary flags:

  • -p: Displays all variables and functions currently marked for export in reusable shell syntax.
  • -n: Removes a variable from the export list while keeping the variable in the current shell.
  • -f: Exports a shell function instead of a variable.

How to Use Export in Linux: Practical Examples

The following examples demonstrate how to use export in common situations.

Example 1: Create and Export a New Variable

The simplest approach is to create a variable and export it with one command. This defines the variable in the current shell and immediately makes it available to child processes.

Use printenv to verify that the variable was exported:

Output

Example 2: Export an Existing Shell Variable

An existing shell variable can be exported separately without changing its value. This approach is useful when a variable is set conditionally before being made available to other processes.

# Define the variable as a shell variable
DB_HOST="localhost"

# Export it so child processes can access it
export DB_HOST

Any script or subprocess started from this shell can now access DB_HOST.

Example 3: Export a Variable and Assign Its Value

Variable creation and export can be combined into one line. This is the pattern most commonly used in shell scripts and configuration files such as .bashrc.

export APP_ENV="production"

Display the value to confirm the assignment:

Output

Example 4: Display Exported Variables with Export -p

The export -p command lists the variables currently marked for export. In Bash, exported functions may also be included. Because the output uses valid shell syntax, it can be redirected to a file and sourced later to recreate the environment.

The abbreviated output may resemble the following:

Output

declare -x HOME="/home/user"
declare -x LANG="en_US.UTF-8"
declare -x LOGNAME="user"
declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
declare -x PWD="/home/user"
declare -x USER="user"

Each entry begins with declare -x, which is Bash notation indicating that the variable has the export attribute.

Example 5: Remove a Variable from the Export List with Export -n

The -n option removes the export attribute from a variable. The variable remains available in the current shell, but newly started child processes no longer inherit it.

export APP_ENV="production"

# Confirm that the variable is exported
printenv APP_ENV

Output

Remove the variable from the export list:

export -n APP_ENV

# The variable remains available in the current shell
echo $APP_ENV

Output

A child process can no longer access the variable:

The command returns no output, showing that the variable is no longer included in the environment passed to child processes.

Example 6: Export a Shell Function with Export -f

Shell functions are normally limited to the shell in which they were defined. A standard variable export does not make a function available to child processes. Bash functions must be exported explicitly with the -f option.

Start by defining a function:

greet() {
  echo "Hello from the function!"
}

Run the function in the current shell:

Output

Export the function with -f:

Start a child Bash process and call the function:

Output

Without export -f, the child shell would report bash: greet: command not found. Function export can be useful in scripts that create subshells and rely on shared helper functions.

Note: Exported functions are a Bash-specific feature and are not portable across different shells. Avoid exporting functions when they are unnecessary, particularly in security-sensitive environments.

Example 7: Modify and Export the PATH Variable

PATH is one of the environment variables most frequently modified with export. It defines the directories the shell searches when a command is entered. Adding a custom directory allows scripts and executable files in that location to be run without specifying their complete paths.

The safe method is to append the new directory to the current value. The existing value is referenced through $PATH:

export PATH="$PATH:/opt/myapp/bin"

Display the updated value:

Output

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/myapp/bin

The additional directory appears at the end of the search order. To make the shell search that directory before the existing locations, place it at the beginning:

export PATH="/opt/myapp/bin:$PATH"

For additional information about managing this variable, see a guide about viewing and updating the Linux PATH environment variable.

How to Preserve Exported Variables Between Sessions

A variable exported from the command line applies only to the current shell session. Closing the terminal removes the variable. To keep the variable available in future sessions, add the relevant configuration to a file that the shell loads automatically.

Add Export Statements to ~/.bashrc

The ~/.bashrc file configures interactive, non-login Bash shells. In many environments, it is loaded whenever a new terminal window or tab opens. It is therefore suitable for variables needed during regular interactive work.

Open the file in a text editor:

Add the export statement at the end:

export MY_API_KEY="your-key-here"

After saving the file, reload it to apply the setting to the current shell without opening another terminal:

New terminal sessions will now define and export MY_API_KEY automatically.

Use ~/.bash_profile for Login Shells

The ~/.bash_profile file, or ~/.profile on some systems, is loaded for login shells. This includes sessions created when signing in to a remote system through SSH. On many desktop installations, ~/.bashrc is enough for most interactive use. Variables required during remote login can instead be configured through ~/.bash_profile.

A common configuration makes ~/.bash_profile load ~/.bashrc, allowing login and interactive shells to share the same settings:

~/.bash_profile
# Add this to the end of ~/.bash_profile
if [ -f ~/.bashrc ]; then
  source ~/.bashrc
fi

Export statements can then remain in ~/.bashrc and will be loaded in both situations.

Configure System-Wide Variables with /etc/environment

Use /etc/environment when a variable must be available to every user instead of only one account. This file is not a shell script. It accepts simple KEY="value" entries and does not use the export keyword.

Open the file with administrative privileges:

sudo nano /etc/environment

Add the required variable:

/etc/environment
JAVA_HOME="/usr/lib/jvm/java-17-openjdk-amd64"

The setting normally becomes available after the next login. Because the file does not depend on shell syntax, it can be used across different shells and display managers. However, not every program reads /etc/environment. For example, services managed by systemd may require separate environment configuration.

Export Compared with Related Commands

Several shell commands provide functionality related to export. Understanding their differences makes it easier to select the appropriate command and avoid scripting errors.

Export vs. Declare -x

In Bash, declare -x VARIABLE and export VARIABLE both assign the export attribute to a variable. Their main differences involve portability and additional features.

Feature export declare -x
POSIX-compliant Yes No, it is Bash-specific
Works in sh and dash Yes No
Supports additional attributes No Yes, including -i for integers and -r for read-only variables

Use export in scripts intended to work with different shells or minimal environments where sh or dash may be the default. Use declare -x in Bash-specific scripts when additional variable attributes are required.

Export vs. Env

The env command has a different purpose. While export changes the environment of the current shell for the duration of the session, env starts one command with a temporary environment and leaves the current shell unchanged.

# export changes the environment of the current shell for the session
export NODE_ENV="production"
node app.js

# env applies the variable only to this command
env NODE_ENV="production" node app.js

The env approach is useful for one-time commands when the current shell environment should remain unchanged. It is also commonly used in interpreter declarations so a script can locate the required interpreter through PATH:

Export vs. Printenv

printenv is a read-only utility that displays environment variables. It does not define or export them. In this comparison, export changes the environment, while printenv inspects it.

# Display one environment variable
printenv HOME

Output

# Display all environment variables
printenv

export -p and printenv often produce similar information, but they are not identical. export -p displays variables that the current shell has marked for export. printenv displays the complete environment available to the process, including variables that may have been defined before the shell started through mechanisms such as /etc/environment or PAM.

Export vs. Set

When used without arguments, set displays shell variables, environment variables, and shell functions. This provides a broader view than export -p. The command does not export values by itself, although its options can change shell behavior.

Use set to inspect everything defined in the current shell. Use export -p to inspect only the values that child processes will inherit.

Using Export in Bash Scripts

Shell scripts frequently need to share environment variables with other scripts or programs. The export command controls which variables are inherited by those child processes.

Pass Variables to Child Scripts

When one Bash script starts another, the child script receives only the variables that the parent exported. Variables that remain local to the parent shell are not passed down.

Consider a parent script that defines two variables and starts another script:

parent.sh

#!/bin/bash

DB_NAME="mydb"
export DB_USER="admin"

bash child.sh

The child script displays both variable values:

child.sh

#!/bin/bash

echo "DB_NAME: $DB_NAME"   # Empty because it was not exported
echo "DB_USER: $DB_USER"   # Displays "admin"

Running parent.sh produces:

Output

Only DB_USER was exported, so it is the only variable available to the child script.

Common Export Patterns in Scripts

Deployment and configuration scripts often load multiple variables from a .env file and export them automatically:

#!/bin/bash
# Load variables from a file and automatically export them

set -a           # Automatically export assigned variables
source .env      # Load KEY=VALUE assignments from the file
set +a           # Disable automatic export

The set -a option causes Bash to mark every subsequent variable assignment for export. This makes it possible to load a .env file without writing a separate export command for each variable. The file must contain valid shell assignment syntax.

For additional shell scripting techniques, see an introductory guide to the Linux terminal.

Troubleshooting Common Export Problems

The following sections describe frequent issues involving exported variables and provide practical ways to identify and correct them.

Variable Is Not Available in a Child Process

If a script cannot access a variable created in the terminal, the variable was probably not exported. As a result, it was not included in the environment passed to the script.

Check whether the variable is exported:

If no matching entry appears, export the variable:

Child processes started afterward can then access the variable.

Variable Disappears After the Terminal Closes

A variable defined and exported interactively remains available only during the current terminal session. Closing the terminal removes it.

To define the variable automatically in future sessions, add the export statement to ~/.bashrc for interactive shells or ~/.bash_profile for login shells. Reload the modified configuration immediately with:

Variable Is Not Passed to Sudo or Cron

Variables from an interactive shell may not be available to commands started through sudo or scheduled through cron. Both typically operate with a restricted environment.

Pass a variable to a command executed with sudo by using env:

sudo env MY_VAR="$MY_VAR" some-command

To request preservation of the current exported environment, use the -E option:

Note: Use sudo -E carefully because it may preserve sensitive variables and altered command paths.

For cron jobs, define required variables directly in the crontab. Open the file with crontab -e and place the assignments before the scheduled commands:

MY_VAR=myvalue
0 2 * * * /path/to/script.sh

For additional information, see a general guide about using cron to automate tasks on Linux.

Commands Stop Working After PATH Is Changed

Running export PATH="/opt/myapp/bin" without retaining the current $PATH replaces the complete search path with one directory. The shell may then be unable to locate standard commands such as ls, cp, or nano, producing command not found errors.

Append or prepend the directory instead of replacing the existing value.

Add the directory to the end:

export PATH="$PATH:/opt/myapp/bin"

Add the directory to the beginning:

export PATH="/opt/myapp/bin:$PATH"

If the current session already contains an unusable PATH, restore a typical default value for that session:

export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

Then correct the persistent entry in ~/.bashrc so that the problem does not return in future terminal sessions. For a detailed explanation, see a guide about viewing and updating the Linux PATH variable.

Command Not Found or Assignment Errors During Export

Shell assignment syntax does not allow spaces around the equals sign. Adding spaces causes the shell to interpret the expression as multiple arguments or commands, which may result in syntax errors or command not found messages.

This syntax is incorrect:

export MY_VAR = "production"

Use the assignment without spaces:

export MY_VAR="production"

The same requirement applies when the variable is created first and exported afterward:

MY_VAR="production"
export MY_VAR

Values containing spaces must be quoted so that the shell treats the entire value as one assignment:

export GREETING="Hello, world"

If a script still cannot access a variable after it has been exported, verify the spelling of the variable name. For example, exporting MY_VAR when the assigned variable is named MY_VARIABLE exports a different name and leaves the intended variable unavailable.

FAQs

What Is the Difference Between a Shell Variable and an Environment Variable in Linux?

A shell variable exists only within the current shell session. It is local to that shell and is not automatically available to scripts or child processes started from it. An environment variable belongs to the process environment and is inherited by child processes.

Use the export command to convert a shell variable into an environment variable. This step is necessary when scripts or commands launched from the current terminal need to read the value.

For a more detailed explanation, see a guide about reading and setting environment and shell variables in Linux.

Does the Export Command Make a Variable Permanent?

No. The export command alone does not preserve a variable permanently. A command such as export MY_VAR="value" applies only to the current shell session. The variable and its export status disappear when that session ends.

To recreate the variable in future sessions, add the export statement to a configuration file such as ~/.bashrc for interactive non-login shells or ~/.bash_profile for login shells. For a system-wide variable, add a compatible assignment to /etc/environment. The variable will then be defined when the relevant session starts.

How Can I View All Currently Exported Variables?

Run export -p to list variables that the current shell has marked for export. Bash presents them using entries such as declare -x VAR="value". The complete process environment can also be displayed with printenv or env.

printenv and env include variables defined by the current shell as well as values inherited from processes and configuration mechanisms that existed before the shell started.

What Does Export -n Do?

The command export -n VARIABLE_NAME removes the export attribute from the named variable. Child processes created afterward no longer inherit it. The variable itself is not deleted and remains available in the current shell.

You can continue reading or changing the variable locally. To make it available to child processes again, export it another time.

Can a Shell Function Be Exported in Bash?

Yes. Bash supports function export through the -f option. Running export -f function_name makes that function available to child Bash processes started by the current shell.

This feature is specific to Bash and does not work in shells such as sh or dash. Exported Bash functions are inherited only by child Bash shells, not by unrelated shells or external programs.

What Is the Difference Between Export and Declare -x?

In Bash, both export VAR and declare -x VAR mark a variable for export. The principal difference is portability. export is POSIX-compliant and works in many shells, including sh, dash, and Zsh. declare -x is a Bash-specific command.

declare also supports additional attributes. For example, -r can mark a variable as read-only, while -i can assign the integer attribute. These capabilities are useful in scripts written specifically for Bash.

Why Is an Exported Variable Missing from a Cron Job?

Cron jobs do not normally receive variables exported in an interactive terminal. Cron starts tasks with a minimal environment that is separate from the user shell.

Define the required variable directly in the crontab opened with crontab -e, or make the scheduled script load a configuration file that defines and exports the variables before executing its main operations.

How Do I Add a Directory to PATH with Export?

To add another directory while retaining all current search paths, use:

export PATH="$PATH:/your/new/directory"

In this command, $PATH represents the existing directory list, the colon separates entries, and /your/new/directory is the location being added. Always retain $PATH unless you intentionally want to replace the complete search path. Omitting it may prevent the shell from finding standard system commands.

To preserve the change between sessions, add the same export statement to ~/.bashrc or another appropriate shell initialization file.

Conclusion

The export command is a fundamental Linux shell tool for managing variables and process environments. Understanding how and when to use it allows variables to be shared with child processes, supports more efficient workflows, and helps create dependable shell scripts and automated tasks.

Exported variables remain active only for the current shell session unless they are defined in a persistent configuration file such as ~/.bashrc, ~/.bash_profile, or /etc/environment. Take particular care when editing persistent configuration files and important variables such as PATH.