Report this

What is the reason for this report?

Linux Export Command: Guide with Examples

Updated on June 10, 2026
Linux Export Command: Guide with Examples

The export command in Linux is a built-in Bash shell command that marks variables and functions so they are passed down to child processes. Without export, a variable you define in your shell stays local to that session and is invisible to any scripts or subprocesses you launch. With export, it becomes an environment variable that child processes can read and use.

In this guide, you will learn how the export command works, explore all of its flags with practical examples, learn how to persist exported variables across sessions, compare export to similar commands, and troubleshoot the most common problems people run into.

Key Takeaways:

  • The export command marks a shell variable as an environment variable, making it available to child processes.
  • A variable defined without export is a shell variable and is invisible to scripts and subprocesses.
  • Use export -p to view all currently exported variables; use export -n to remove a variable from the export list without deleting it; use export -f to export shell functions.
  • Variables exported with export in a terminal session are lost when the session ends. To persist them, add the export statement to ~/.bashrc, ~/.bash_profile, or /etc/environment.
  • For modifying PATH, always use export PATH="$PATH:/new/directory" to append, rather than overwriting the existing value.
  • export is POSIX-compliant and portable across shells. declare -x is bash-specific but offers additional type attributes. Use env VAR=value command when you need to set a variable for a single command without affecting your current shell.
  • Neither sudo nor cron inherit your shell environment by default. Pass variables explicitly or define them in the crontab file.

What is the export command in Linux?

The export command is a POSIX-standard shell built-in available in POSIX-compatible shells such as bash, sh, dash. Other shells like zsh also support export for compatibility. Its primary job is to promote a shell variable to an environment variable, making it part of the environment that gets inherited by child processes.

To understand why this matters, let’s understand the difference between the two types of variables.

Shell variables vs. environment variables

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

GREETING="Hello, world"

You have created a shell variable. It exists only in your current shell session. If you open a new terminal tab, run a script, or launch a subprocess, that variable will not be there.

An environment variable, on the other hand, is part of a process’s environment (a set of key-value pairs that the operating system passes to every process when it starts). When you launch a child process from your shell, it receives a copy of the parent shell’s environment. Common examples of environment variables you are probably already using include PATH, HOME, and USER.

Note: Variable assignments in shell syntax must not contain spaces around the = sign.

MY_VAR=value    # Correct
MY_VAR = value  # Incorrect

The export command is the bridge between these two worlds. It takes a shell variable and adds it to the environment, so any child process spawned from the current shell will inherit it.

How export makes variables available to child processes

Here is a simple example of why export is necessary. Say you define a variable and then run a script that tries to use it:

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

The output will be blank because MY_VAR was never exported to the environment. Now compare that to this:

# With export
export MY_VAR="digitalocean"
bash -c 'echo $MY_VAR'
Output
digitalocean

The child bash process can see the variable because it was included in the environment it inherited.

One important thing to note: inheritance only flows downward. A child process gets a copy of the parent’s environment, but any changes it makes to that copy do not travel back up to the parent. If a script you run modifies MY_VAR, your current shell will not see that change.

Basic syntax of the export command

The general syntax for export is:

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

You can export a variable that already exists, or declare and export it in a single step.

Syntax breakdown

Here’s a breakdown of the main components in the export command’s syntax and what each part means:

Component Description
export The built-in command
NAME The variable or function name to export
=VALUE Optional. Assign a value at the same time as exporting
options Flags that modify behavior (-p, -n, -f)

export command flags

The export command supports three flags:

  • -p: Print a list of all currently exported variables and functions in a format that can be reused as shell input.
  • -n: Remove a variable from the export list without deleting it from the current shell session.
  • -f: Export a shell function (rather than a variable) to child processes.

How to use export in Linux: Step-by-step examples

Below, you’ll find practical examples and use cases to help you understand how to use the export command in different scenarios.

Example 1: Create and export a new variable

The most straightforward use is declaring a variable and exporting it in a single command. This sets the variable in the current shell and immediately marks it for export to any child processes.

export PROJECT="my-app"

To confirm the variable was exported successfully, use printenv:

printenv PROJECT
Output
my-app

Example 2: Export an existing shell variable

If you already have a shell variable defined, you can export it separately without redefining its value. This is useful when you want to set a variable conditionally before deciding to export it.

# First, define the variable as a shell variable
DB_HOST="localhost"

# Then export it to make it available to child processes
export DB_HOST

Now any script or subprocess you launch from this shell will be able to read DB_HOST.

Example 3: Export a variable with a value in one step

You can combine declaration and export into a single line. This is the most common pattern in shell scripts and .bashrc configuration files.

export APP_ENV="production"

Verify it was set:

echo $APP_ENV
Output
production

Example 4: View all currently exported variables with export -p

Running export -p prints variables currently marked for export. In Bash, exported functions may also appear. The output is formatted as valid shell syntax, so you could redirect it to a file and source it later to restore the same environment.

export -p

The output will look something like this (truncated for brevity):

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

Each line starts with declare -x, which is the shell’s internal notation for an exported variable.

Example 5: Remove a variable from the export list with export -n

The -n flag does the opposite of export: it removes a variable from the export list. The variable still exists in your current shell session, but child processes will no longer inherit it.

export APP_ENV="production"

# Verify it is exported
printenv APP_ENV
Output
production

Remove it from the export list:

export -n APP_ENV

# The variable still exists in this shell
echo $APP_ENV
Output
production

But child processes can no longer see it:

bash -c 'echo $APP_ENV'

The last command produces no output, confirming the variable is no longer in the environment passed to child processes.

Example 6: Export a shell function to child processes with export -f

By default, shell functions are even more local than shell variables. They do not get inherited by child processes at all, even with a plain export. To export a function, you must use the -f flag explicitly.

First, define a function:

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

Call it in the current shell to confirm it works:

greet
Output
Hello from the function!

Now export it with -f:

export -f greet

Open a child shell and call the function:

bash -c 'greet'
Output
Hello from the function!

Without the export -f step, that last command would return bash: greet: command not found. Exporting functions is particularly useful in scripts that invoke subshells and need shared helper functions to be available throughout.

Note: Exported functions are Bash-specific and are not portable across shells. In security-sensitive environments, avoid exporting functions unnecessarily.

Example 7: Modify and export the PATH variable

PATH is one of the most commonly modified environment variables. It tells the shell which directories to search when you type a command. Adding a custom directory to PATH lets you run scripts or binaries from that directory without typing the full path every time.

The safe way to extend PATH is to append your new directory to the existing value, using $PATH to reference what is already there:

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

You can verify the change:

echo $PATH
Output
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/myapp/bin

The new directory is now at the end of the search list. If you want it checked first (for example, to override a system binary with your own version), put it at the beginning:

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

For more detail on working with the PATH variable, see How To View and Update the Linux PATH Environment Variable.

How to persist exported variables across sessions

A critical limitation of export is that it only applies to the current shell session. When you close the terminal, all exported variables are gone. To make a variable permanent, you need to add the export statement to a shell configuration file that gets sourced automatically when a new session starts.

Adding export to ~/.bashrc

~/.bashrc is the configuration file for interactive non-login bash shells. In practice, this is the file that runs every time you open a new terminal window or tab. It is the right place for variables you want available in your everyday interactive sessions.

Open the file with a text editor:

nano ~/.bashrc

Scroll to the bottom and add your export statement:

export MY_API_KEY="your-key-here"

Save and close the file. To apply the change to your current session without opening a new terminal, source the file:

source ~/.bashrc

Any new terminal session will now have MY_API_KEY available automatically.

Using ~/.bash_profile for login shells

~/.bash_profile (or ~/.profile on some systems) is read for login shells, such as sessions started when you log in to a server via SSH. On many desktop Linux systems, ~/.bashrc is sufficient for most use cases. However, if you are setting variables that need to be available when logging in remotely, ~/.bash_profile is the right place.

A common practice is to have ~/.bash_profile source ~/.bashrc, so both login and interactive shells share the same variables:

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

Then add all your export statements to ~/.bashrc and they will be picked up in both contexts.

System-wide variables with /etc/environment

If you need a variable available to all users on the system (not just your own account), /etc/environment is the appropriate place. Unlike .bashrc, this file is not a shell script. It uses a simple KEY="value" format without the export keyword.

Open the file with root privileges:

sudo nano /etc/environment

Add your variable:

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

Save and close the file. The change takes effect after the next login. Because this file is not shell syntax, it works across different shells and display managers, making it useful for system-level configuration. Note that not all programs read /etc/environment. Services started by systemd, for instance, may need their environment configured separately.

Several other commands overlap with export in function. Understanding the differences will help you choose the right tool and avoid common scripting mistakes.

export vs. declare -x

In bash, declare -x VARIABLE is functionally equivalent to export VARIABLE. Both mark the variable for export to child processes. The difference is portability and expressiveness:

Feature export declare -x
POSIX-compliant Yes No (bash-specific)
Works in sh, dash Yes No
Supports extra attributes No Yes (e.g., -i for integer, -r for readonly)

Use export in scripts that need to run on different shells or in minimal environments (like Docker containers or CI runners that may default to sh or dash). Use declare -x in bash-specific scripts when you also need to set type attributes.

export vs. env

The env command serves a different purpose. While export marks variables in your current shell session, env runs a single command with a temporary, modified environment without changing your current shell at all.

# export: modifies the current shell environment persistently (for the session)
export NODE_ENV="production"
node app.js

# env: runs the command with that variable set, then discards it
env NODE_ENV="production" node app.js

The env approach is cleaner for one-off commands where you do not want to pollute your current shell environment. It is also useful in #! (shebang) lines at the top of scripts to ensure you are using the correct interpreter regardless of where it is installed:

#!/usr/bin/env python3

export vs. printenv

printenv is a read-only utility for displaying environment variables. It does not set or export anything. You can think of it as the inspection tool, while export is the setter.

# Print a single variable
printenv HOME
Output
/home/sammy
# Print all environment variables
printenv

Running export -p and printenv will show similar information, but there is a subtle difference: export -p only shows variables exported by the current shell, while printenv shows the full environment that was passed to the current process (which may include variables set before the shell started, such as those from /etc/environment or PAM).

export vs. set

The set command (with no arguments) lists all shell variables, environment variables, and functions, which is a much broader view than export -p. It does not set or export anything on its own (though set with flags controls shell behavior options). Use set when you want to see everything in the current shell; use export -p when you want to see only what will be passed to child processes.

Using export in Bash scripts

When writing bash scripts, environment variables often need to be shared across multiple scripts or processes; this is where the export command plays an essential role.

Passing variables to child scripts

When a bash script calls another script, the child script only inherits variables that were exported. This is a common source of confusion for people new to shell scripting.

Consider two scripts. The first sets a variable and calls the second:

parent.sh
#!/bin/bash

DB_NAME="mydb"
export DB_USER="admin"

bash child.sh

The second script which prints the values of the variables:

child.sh
#!/bin/bash

echo "DB_NAME: $DB_NAME"   # will be empty
echo "DB_USER: $DB_USER"   # will print "admin"

Running parent.sh:

Output
DB_NAME:
DB_USER: admin

Only DB_USER was exported, so only it is visible in the child script.

Common scripting patterns with export

A typical pattern in deployment or configuration scripts is to load variables from a .env file and export them all at once:

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

set -a           # Automatically export all variables that are assigned
source .env      # Source the file (assigns all KEY=VALUE pairs)
set +a           # Turn off automatic export

The set -a flag tells bash to automatically mark every variable assignment as exported. This is a convenient way to load a .env file without writing a separate export for every variable. This approach only works when the .env file uses valid shell assignment syntax.

For more on bash scripting patterns, see An Introduction to the Linux Terminal.

Troubleshooting common export issues

In this section, we’ll outline some of the most common issues you might face when working with exported variables and also provide clear explanations and practical fixes, so you can troubleshoot and resolve export-related problems.

Variable not available in child process

If you run a script and cannot access a variable that you set in your terminal, it usually means the variable was not exported and therefore is not part of the environment passed to the script. To check if a variable is exported, use:

export -p | grep DB_HOST

If the variable is missing from the output, you can export it like this:

export DB_HOST

This will make the variable available to any child processes.

Variable lost after terminal session ends

When you set and export a variable, it only lasts for the current terminal session. If you close the terminal and open a new one, the variable will not be available. To make a variable available in all future sessions, add the export statement to your ~/.bashrc file (for interactive shells) or ~/.bash_profile (for login shells). After modifying the file, you can immediately apply the changes with:

source ~/.bashrc

Variable not passed to sudo or Cron

Variables you set in your shell session may not be available when running commands with sudo or through cron jobs. This is because both sudo and cron start with a minimal environment.

To pass a variable with a sudo command, you can use the env command:

sudo env MY_VAR="$MY_VAR" some-command

If you want to preserve your entire environment (including all exported variables) when running a command with sudo, you can use the -E flag. Be careful, as this will pass all environment variables to the command:

sudo -E some-command

Note: Use sudo -E carefully because it preserves the entire environment, including potentially sensitive variables and modified paths.

When creating cron jobs, variables must be defined directly in your crontab file. Use crontab -e to open your crontab for editing and add your variables at the top before your scheduled tasks:

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

For more on working with cron, see How To Use Cron to Automate Tasks on Ubuntu.

Commands stop working after changing PATH

If you run export PATH="/opt/myapp/bin" without including the existing $PATH value, you replace the entire search path with a single directory. Your shell can no longer find standard utilities such as ls, cp, or nano, and you may see errors like command not found for basic commands.

The fix is to append or prepend instead of overwrite. To add a directory at the end:

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

To add it at the beginning:

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

If you already overwrote PATH in the current session, you can restore a sensible default for this shell only:

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

Then update ~/.bashrc with the correct append form so the mistake does not return the next time you open a terminal. For a deeper walkthrough, see How To View and Update the Linux PATH Environment Variable.

command not found or assignment errors when exporting

Shell assignment syntax is strict. Spaces around the = sign turn a simple export into something the shell parses as separate commands, which often produces command not found or other syntax errors.

This fails:

export MY_VAR = "production"

Use this form instead:

export MY_VAR="production"

The same rule applies when you define a variable first and export it later: assign without spaces, then export by name:

MY_VAR="production"
export MY_VAR

Values that contain spaces must stay inside quotes, or the shell will treat each word as a separate argument:

export GREETING="Hello, world"

If a script still cannot see the variable after you export it, double-check the variable name. A typo in the export line (for example, export MY_VAR when the variable was set as MY_VARIABLE) leaves the intended name unexported while exporting a different, empty name.

FAQ

1. What is the difference between a shell variable and an environment variable in Linux?

A shell variable is a value that exists only inside the current shell session. It is local and cannot be accessed by any child processes or scripts started from that shell. In contrast, an environment variable is stored in the process environment and is automatically inherited by all child processes spawned from that shell.

To turn a shell variable into an environment variable, you use the export command. This step is essential if you want child processes (such as scripts or commands you run in the same terminal) to see and use the variable.

For a more thorough explanation of environment and shell variables, check out How To Read and Set Environmental and Shell Variables on Linux.

2. Does the export command make a variable permanent?

No, the export command does not make a variable permanent by itself. If you run export MY_VAR="value" in a terminal, that setting is active only for your current shell session. Once you close the window or end the session, the variable (and its export status) disappears.

To keep it across all future terminal sessions, you need to add the export statement to a configuration file such as ~/.bashrc (for interactive non-login shells), ~/.bash_profile (for login shells), or /etc/environment (for a system-wide effect). The next time you open a shell, your variable will be automatically set and exported.

3. How do I view all currently exported variables?

To list all variables that are currently marked for export in your shell, use export -p. This displays every exported variable, formatted as declare -x VAR="value" lines. You can also see the overall environment your shell passes on by running either printenv or env.

Note that printenv and env show the current environment, which includes both variables set in your shell and any values inherited from parent processes that started the shell.

4. What does export -n do?

When you run export -n VARIABLE_NAME, you remove that variable from the export list. This means the variable will no longer be available to child processes started from the current shell. However, this does not unset or delete the variable itself; it simply stops it from being part of the environment that gets passed down. You’ll still be able to use or change the variable in your current shell session, but subprocesses won’t see it unless you export it again.

5. Can I export a shell function in bash?

Yes, Bash allows you to export functions using the -f flag. When you run export -f function_name, the named function becomes available in any child Bash instances started from your current shell.

Keep in mind, though, that this is specific to Bash an doesn’t work in shells like sh or dash. Also, such exported functions are only inherited by child Bash shells and not by other types of shells or external processes.

6. What is the difference between export and declare -x?

In Bash, both export VAR and declare -x VAR accomplish the same thing: they mark VAR for export, making it available to child processes. The main difference is in portability and capabilities. export is POSIX-compliant, making it work across a wide range of shells (sh, dash, zsh, etc.), while declare -x is specific to Bash.

However, declare -x provides extra options, such as marking a variable read-only (-r) or as an integer (-i), which are helpful in Bash-specific scripting scenarios.

7. Why is my exported variable not available in a cron job?

Even if you export a variable in your terminal, cron jobs won’t have access to it by default. This is because cron starts with a minimal environment, completely separate from your user shell. Variables exported in your terminal are not passed on.

To use a variable in a cron job, you have to define it within your crontab file (which you edit using crontab -e) or ensure your cron-executed script sources a configuration file that sets these variables before running its main tasks.

8. How do I add a directory to the PATH variable using export?

To add a new directory to your PATH while keeping the existing search paths, use:

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

Here, $PATH refers to the existing list of directories, the colon : separates them, and /your/new/directory is the folder you want to add. It is important always to include $PATH when updating this variable, or you might accidentally erase all other paths and lose access to system commands. If you want this change to last across future sessions, add the export line to your ~/.bashrc or similar shell initialization file.

Conclusion

The export command is one of the foundational tools for working with variables and managing your shell environment in Linux. By knowing when and how to use export, you can make variables available to child processes, adjust your workflow, and write more reliable shell scripts and automation jobs. Remember, exported variables only last as long as your current session unless you add them to a configuration file like ~/.bashrc, ~/.bash_profile, or /etc/environment. Always be careful when editing persistent files, especially with variables like PATH.

With a clear understanding of export and its options, you’re ready to confidently set environment variables, troubleshoot common issues, and customize your shell environment for almost any use case. If you want to deepen your understanding of shell environment variables, scripting, and command-line workflows, here are some tutorials you can check out:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Anish Singh Walia
Anish Singh Walia
Author
Sr Technical Content Strategist and Team Lead
See author profile

I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix

Manikandan Kurup
Manikandan Kurup
Editor
Senior Technical Content Engineer I
See author profile

With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.

Category:

Still looking for an answer?

Was this helpful?

Good info. I have a command where it says “export MY_KERNEL =/root/xyz/Linux-v4.12/” and then compiling a make file by command “make KDIR=$MY_KERNEL -j8”. what does it mean. I am able to compile the make file using just “make” command only. what is the difference in compiling make file with normal “make” and “make KDIR=$MY_KERNEL -j8”. Please help me

- GSK

Thank you so much Pankaj, it will help a lot.

- Rahul Bhichher

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.

Dark mode is coming soon.