Exporting Variables with export

Su Suriya Ravichandran Updated 06 Dec 2026
5 min read ·Lesson 38 of 205

The export built-in command marks a variable so that Bash passes it, with its value, to every program it starts afterward. Exporting is what turns an ordinary shell variable into an environment variable.

Syntax

export has several forms:

export NAME              # export a variable that already exists
export NAME=value        # assign and export in one step
export A=1 B=2           # several at once
export -p                # list exported variables
export -n NAME           # remove the export attribute
export -f function_name  # export a function

declare -x NAME=value has the same effect as export NAME=value. The -x stands for "export".

Assigning and Exporting in One Step

The most common form assigns a value and exports the variable in the same command:

export V2=assigned_and_exported
declare -p V2
declare -x V2="assigned_and_exported"

The declare -p output confirms the -x attribute. Notice that there are no spaces around the equals sign, which is required in every Bash assignment. Quote the value if it contains spaces:

export TITLE="My Big Report"
bash -c 'echo "child TITLE=[$TITLE]"'
child TITLE=[My Big Report]

Exporting an Existing Variable

You can assign a variable first and export it later. Compare the attributes before and after:

V1=plain
declare -p V1
export V1
declare -p V1
declare -- V1="plain"
declare -x V1="plain"

The variable keeps its value, and only its attribute changes.

Exporting Marks the Variable, Not the Value

When you export a variable, Bash does not freeze its value. The variable carries the export attribute from then on, and each program you start receives whatever the variable holds at that moment. A later assignment, even one without export, keeps the attribute:

export NUM=1
NUM=2
bash -c 'echo "child NUM=$NUM"'
child NUM=2

The second line assigned 2 with no export in front, yet the child received 2. You only need to export a name once.

Exporting Before a Variable Has a Value

export NAME also works on a name that has not been assigned yet. Bash remembers the attribute, but the variable has no value, so it does not appear in the environment until it gets one:

unset NEWV
export NEWV
declare -p NEWV
printenv NEWV
echo "printenv status=$?"
declare -x NEWV
printenv status=1

declare -p shows the attribute without a value, and printenv finds nothing. As soon as you write NEWV=hello, the variable enters the environment because the export attribute was already waiting.

Listing Exported Variables

export -p prints every exported variable in a form that you can paste back into a script. Filter it with grep to look at a few names:

export -p | grep -E ' (V1|V2|NUM)='
declare -x NUM="2"
declare -x V1="plain"
declare -x V2="assigned_and_exported"

Plain env shows the same variables as NAME=value lines:

env | grep -E '^(V1|V2|NUM)=' | sort
NUM=2
V1=plain
V2=assigned_and_exported

Exporting Does Not Affect the Parent

Exporting sends a value down to child processes only. A script that exports a variable cannot change the shell that started it, because the script runs as a child. If you need a script to change variables in your current shell, run it with source, as covered in the lesson on running scripts in different ways.

Removing the Export Attribute

The -n option removes the attribute but keeps the variable and its value in the current shell:

export SHARED="visible"
export -n SHARED
bash -c 'echo "child SHARED=[${SHARED-unset}]"'
echo "shell SHARED=[$SHARED]"
child SHARED=[unset]
shell SHARED=[visible]

To remove a variable completely, use unset, which a later lesson covers.

Exporting Functions

Functions can be exported too, with export -f. A child Bash then knows the function by name:

add() { echo $(( $1 + $2 )); }
export -f add
bash -c 'add 2 3'
5

The function body travels through the environment, so the child Bash could call add as if it had defined it. This works only between Bash shells. Other languages and other shells do not understand exported Bash functions. Exported functions are also a surprising entry point for security problems, a topic that comes back in the security lessons, so use them sparingly.

Arrays Cannot Be Exported

The environment can hold only text, and Bash has no way to pass an array through it. Bash accepts the command, but the child sees nothing:

arr=(a b c)
export arr
declare -p arr
bash -c 'echo "child arr=[${arr-unset}] length=${#arr[@]}"'
declare -ax arr=([0]="a" [1]="b" [2]="c")
child arr=[unset] length=0

The attribute -a (array) and -x (export) both appear in the parent, but the child did not receive the array. To pass a list, build one string, for example with spaces or colons between the items, and split it in the child. The PATH variable uses exactly this approach, with colons.

Invalid Names

export checks the name before it does anything else:

export 1abc=5
export: `1abc=5': not a valid identifier

The message appears for any name that breaks the naming rules from an earlier lesson, such as one that starts with a digit or contains a hyphen.

A Practical Example

A script often passes a setting to another script by exporting it. The first script below reads a mode and starts a second script, and the second script reads the same setting from its environment:

cat > report.sh <<'EOF'
#!/usr/bin/env bash
echo "report: LOG_LEVEL=${LOG_LEVEL:-info}"
EOF
chmod +x report.sh

LOG_LEVEL=debug ./report.sh
./report.sh
report: LOG_LEVEL=debug
report: LOG_LEVEL=info

The first call supplied LOG_LEVEL for one command only, using a prefix assignment. The second call found no value and used the default info. If the variable had been exported earlier with export LOG_LEVEL=debug, every later call would have seen debug until the shell closed.

How Long an Export Lasts

An export lasts as long as the shell in which you ran it. When you close the terminal, the variable disappears. To make a variable available in every new terminal, put the export line into one of Bash's startup files, which a later lesson covers.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Exporting Variables with export and get answers drawn from it.

Signed-in readers only.