• Shell Scripting
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question

How to Defining a Bash Variable With or Without ‘export’ in Linux

A variable is a basic building block that stores a value at a specific memory location, and every operation performed on a variable affects that memory location. Values ​​stored in variables can be changed or deleted during program execution. The main difference with bash variables is that they don’t need to be declared. Just assign the value of the variable using the variable name.

In Linux bash commands and scripts, there are two different ways to define variables:

  • with export command (also known as environment variable )
  • without export command (also known as shell variable ).

What is Shell Variable?

Shell variables are local variables whose value we can only access within that shell. There are many uses for shell variables, some of which are listed below:

  • Shell variables are used as counter variables in Loop.
  • Shell variables are also used as temporary variables to store values.

Syntax for declaring Shell Variable:

bash export vs variable assignment

What is Environmental Variable?

Environment variables are variables whose values ​​are set globally in a program and can be inherited by subshells, processes, and commands. Environment variables have many uses, some of which are listed below:

  • It Configures the environment of the subprocess or shell
  • It defines the variables that will be used by the bash script run from the parent shell.
  • Set environment variables for terminal multiplexer such as screen or tmux.
  • It is used for Configuring the environment for building scripts and build tools

Syntax for declaring Environmental Variable:

bash export vs variable assignment

The main difference between the two is that the export command makes the variable available to all subsequent commands run in that shell.

Relationship Between Parent Shell and Sub Shell

The parent shell can export its variables to the subshell environment. A subshell cannot export or modify its variables back to the parent shell.
The parent shell has a special ability to copy exported variables and their values ​​when the subshell is created.  The subshell keeps a copy of this environment variable.
Variables exported from the subshell are not available in the parent shell. Variables exported from a subshell are only available in the children of subsequent subshells.

More on Export Command 

Exporting bash functions.

The Export command can also be used to export bash functions.

Step 1 : Create a Bash Function

bash export vs variable assignment

Step 2 : We can use the export -f command line option to export functions so that they are also available in subshells and processes:

The function is now available in sub-shells.

bash export vs variable assignment

Removing the value of an Exported Variable

For removing the value of an exported variable we can use the unset command which is in-built bash command that can be used to delete the value of an exported variable.

bash export vs variable assignment

Viewing All Exported Variables

Step 1 : If the export command takes no arguments, it displays a list of all variables. To export all listed variables to the subprocess, use the -p option.

bash export vs variable assignment

Step 2 : With the help of the below command, we can undo the effects of exporting -p command.

The variable is again restricted to the current shell session.

More on Bash Script and Export

In order to get the expected results with the export command when creating a bash script, we need to keep the following points in mind:

Export when running a bash script

Suppose you run a bash script in its own subshell inside a bash command that contains an export command. So the variables exported from the script are only used in the subshell, not the parent shell.

Step 1 : You can easily create a file to store your script (“outscript.sh”) with the following command:

bash export vs variable assignment

Step 2 : With the help of “chmod +x”, we can load “outscript.sh” into bash and run it.

 Exported variables disappear from the environment.

bash export vs variable assignment

Source Variables From a Bash Script to the Current Shell

As shown above, we know that the bash script will never export its exported variables back to the calling shell, but the bash script also provides us with a command that can handle this situation easily. The source command allows us to load variables and functions into the bash shell and use them in the current shell without creating a subshell.

Step 1: You can easily create a file to store your script (“outscript.sh”) with the following command:

Step 2 : With the help of “source”, we can load “outscript.sh” into bash and run it.

bash export vs variable assignment

Please Login to comment...

Similar reads.

  • Technical Scripter
  • Bash-Script
  • Technical Scripter 2022
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

What's the difference between set, export and env and when should I use each?

Every so often I'll bash out a bash script and it strikes me there are a few ways of setting a variable:

When you're inside a script or a single command (for instance, I'll often chain a variable with a Wine launcher to set the right Wine prefix) these seem to be completely interchangeable but surely that can't be the case.

What's the difference between these three methods and can you give me an example of when I would specifically want to use each one?

Definitely related to What is the difference between `VAR=...` and `export VAR=...`? but I want to know how env fits into this too, and some examples showing the benefits of each would be nice too :)

  • command-line

Community's user avatar

  • 9 Note that export key=value is extended syntax and should not be used in portable scripts (i.e. #! /bin/sh ). –  Simon Richter Commented Oct 24, 2012 at 11:49

Let us consider a specific example. The grep command uses an environment variable called GREP_OPTIONS to set default options.

Now. Given that the file test.txt contains the following lines:

running the command grep one test.txt will return

If you run grep with the -v option, it will return the non-matching lines, so the output will be

We will now try to set the option with an environmental variable.

Environment variables set without export will not be inherited in the environment of the commands you are calling.

The result:

Obviously, the option -v did not get passed to grep .

You want to use this form when you are setting a variable only for the shell to use, for example in for i in * ; do you do not want to export $i .

However, the variable is passed on to the environment of that particular command line, so you can do

which will return the expected

You use this form to temporarily change the environment of this particular instance of the program launched.

Exporting a variable causes the variable to be inherited:

returns now

This is the most common way of setting variables for use of subsequently started processes in a shell

This was all done in bash. export is a bash builtin; VAR=whatever is bash syntax. env , on another hand, is a program in itself. When env is called, following things happen:

  • The command env gets executed as a new process
  • env modifies the environment, and
  • calls the command that was provided as an argument. The env process is replaced by the command process.

This command will launch two new processes: (i) env and (ii) grep (actually, the second process will replace the first one). From the point of view of the grep process, the result is exactly the same as running

However, you can use this idiom if you are outside of bash or don't want to launch another shell (for example, when you are using the exec() family of functions rather than the system() call).

Additional note on #!/usr/bin/env

This is also why the idiom #!/usr/bin/env interpreter is used rather than #!/usr/bin/interpreter . env does not require a full path to a program, because it uses the execvp() function which searches through the PATH variable just like a shell does, and then replaces itself by the command run. Thus, it can be used to find out where an interpreter (like perl or python) "sits" on the path.

It also means that by modifying the current path you can influence which python variant will be called. This makes the following possible:

instead of running Python, will result in

Pablo Bianchi's user avatar

  • 4 Why does GREP_OPTIONS='-v' grep one test.txt work? I thought it needed a semicolon after '-v' (but I tried it and it does in fact work.) –  Joe Commented Oct 26, 2012 at 6:20
  • 9 Because with a semicolon, it is interpreted as two separate bash commands; the first one sets the variable (without exporting it), and the second starts with an environment that doesn't have the variable exported. Without the semicolon, however, this is one command (grep), preceded by setting a local environment. –  January Commented Oct 26, 2012 at 7:05
  • 1 @Pithikos Environment variables are set by "sourcing an environment." By default, bash will source a system-wide bashrc (or profile.d or bash_profile). Then it sources your user ~/.bashrc (and/or ~/.bash_profile). Either of these files can contain bash commands to source other scripts, so you can ultimately have environment variables coming from all over the place. –  Eric Commented Mar 3, 2016 at 21:27
  • 26 What about set var=blah ? –  CMCDragonkai Commented Jan 11, 2017 at 3:20
  • 4 I think you should emphasize that env also doesn't affect the current shell environment variables ( env changes the environment variables in a new process). I looked at another post and clarify that by myself. –  Rick Commented Dec 31, 2021 at 7:37

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged command-line bash ..

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities

Hot Network Questions

  • How do I remove a wheel axle with smooth circular bolts?
  • Seeking a Text-Based Version of Paul Dirac's 1926 Paper on Quantum Mechanics
  • Would a scientific theory of everything be falsifiable?
  • I have been trying to solve this Gaussian integral, which comes up during the perturbation theory
  • What makes amplifiers so expensive?
  • Missed the application deadline for a TA job. Should I contact them?
  • Are these colored sets closed under multiplication?
  • One-line negative review
  • Hungarian Immigration wrote a code on my passport
  • How can I calculate derivative of eigenstates numerically?
  • Is it possible/recommended to paint the side of piano's keys?
  • What was the newest chess piece
  • A coworker says I’m being rude—only to him. How should I handle this?
  • '05 Scion tC, bought used. 145k miles , unknown if spark plugs were ever changed. Should I change 'em?
  • Fantasy novel where a brother and sister go to a fantasy and travel with a one-armed warrior
  • Has Macron's new government indicated whether it is "leaning" hard left or hard right?
  • Fill this Sudoku variant so that the sums of numbers in the outlined regions are all different
  • Sum of the individual kinetic energies of the particles which make the system the same as the K.E. of the center of mass? What's bad in my reasoning?
  • Seeking an explanation for the change in order of widening operations from .NET Framework 4.8 to .NET 8
  • Why is the Liar a problem?
  • Is internal energy depended on the acceleration of the system?
  • Why doesn't Wolfram Alpha give me the correct answer for this?
  • Coloring a function based on its monotonicity
  • Modifying Expansion Order with \seq put right

bash export vs variable assignment

  • PHOENIXNAP HOME
  • Colocation Overview
  • Data Center as a Service Solutions for Digital Transformation
  • Hardware as a Service Flexible Hardware Leasing
  • Meet-Me Room The Interconnectivity Hub
  • Schedule a Tour Guided Virtual Data Center Tour
  • Data Center Locations Global Data Center Footprint
  • Platform Overview
  • Rancher Deployment One-Click Kubernetes Deployment
  • Intel Xeon E-2300 Entry-Level Servers
  • 4th Gen Intel Xeon Scalable CPUs Boost Data-Intensive Workloads
  • Alliances Technology Partnerships
  • Object Storage S3-Compatible Storage Solution
  • Dedicated Servers Overview
  • FlexServers Vertical CPU Scaling
  • Intel Xeon-E Servers Intel Xeon 2200 Microarchitecture
  • GPU Servers Servers with NVIDIA Tesla GPUs
  • Dedicated Servers vs. BMC Compare Popular Platforms
  • Promotions See Available Discounts
  • Buy Now See All Servers
  • Managed Private Cloud (MPC) Highly Customizable Cloud
  • Data Security Cloud Secure-By-Design Cloud
  • Hybrid Cloud Multi-Platform Environment
  • Edge Computing Globally Distributed Servers
  • Object Storage S3 API Compatible Storage Service
  • Bare Metal Cloud API-Driven Dedicated Servers
  • Alternative Cloud Provider Overcome Public Cloud Limitations
  • Backup Solutions Veeam-Powered Services
  • Disaster Recovery VMware, Veeam, Zerto
  • Veeam Cloud Connect Backup and Replication
  • Managed Backup for Microsoft 365 Veeam-Powered Service
  • Data Security Cloud Secure-by-Design Cloud
  • Encryption Management Platform (EMP) Cryptographic Key Management
  • Confidential Computing Data-in-Use Encryption
  • Ransomware Protection Data Protection and Availability
  • DDoS Protection Network Security Features
  • CONTACT SUPPORT
  • Network Overview Global Network Footprint
  • Network Locations U.S., Europe, APAC, LATAM
  • Speed Test Download Speed Test
  • Blog IT Tips and Tricks
  • Glossary IT Terms and Definitions
  • Resource Library Knowledge Resources
  • Events Let's Meet!
  • Newsroom Media Library
  • Developers Development Resources Portal
  • APIs Access Our Public APIs
  • GitHub Public Code Repositories
  • Search for:

Bash Export Variable

Home » SysAdmin » Bash Export Variable

Introduction

Shell variables are key-value pairs used to store important configuration data for the shell. Given that a variable is just a pointer to a piece of data, it can contain a reference to any data type - a name, number, filename, or even another variable.

All the variables the user defines inside the bash shell are local by default. It means that the shell's child processes do not inherit the shell's variables. The user must export the variables to make them available to child processes.

This tutorial will show you how to export Bash variables in Linux using the export command.

How to export Bash variable

Prerequisites

  • Access to the terminal/command line.
  • The bash shell.

What Does the export command in Bash do?

Variables in Bash are created using the declare command or by simply typing the key-value pair in the shell. For example, to create a variable named test , which has a string value of example , type:

To see the value of a variable, use the echo command :

The value appears in the output:

Printing the value of a variable using the echo command.

However, the variable created in this way applies only to the current shell session. To test this, open a child shell by typing:

Use echo to check the variable.

The output is empty because the variable test has a value only in the parent shell. A variable needs to be exported to be used in child processes.

The variable set in the parent shell is not visible in the child shell.

Exporting variables is also important for Bash scripting. The example below creates a script named test-script.sh that displays the value of the test variable.

1. Create the file using a text editor such as nano :

2. Type the following into the file:

3. Save the file and exit.

4. Change the permissions of the file to allow it to be executed:

5. Execute the script:

The script returns an empty output.

Running the test script without exporting the variable it should print.

The output is empty because the script is executed in a child shell that is automatically opened upon executing the script.

How to Export Bash Variable

The syntax for the export command is simple:

The example below confirms that the test variable exists even after using bash to start a new shell session.

After the export command, the shell variable is visible in the child shell.

The scripts now also have access to the variable. Execute the previously created script again.

It now correctly outputs the value of test .

Running the test script after the variable has been exported.

Note : Variables can be created and exported in the same line. To do this, use the following syntax:

The variable created this way is automatically exported to child processes.

Exporting Functions

Use the export command to export bash functions .

1. For example, create a bash function called echoVar :

2. The function calls echo to display the value of the test variable:

Creating a function in the Bash shell.

3. The function can now be called by its name to display the value of the variable. To make the function available in child processes, type:

The function is now available in child shells.

Executing the function in a child process.

Viewing All Exported Variables

When the export command is issued with no arguments, it displays the list of all variables. To export all the listed variables to child processes, use the -p option.

Exporting and displaying all the shell variables with the export -p command.

The two variables created in this article are at the bottom of the output.

Finding the two previously created variables in the output of the export -p command.

To undo the effect of export -p , use the -n option.

The variables are again limited to the current shell session.

Note : Environment variables are system configuration variables present in all major operating systems. Read the following articles to learn how to set them up in Windows , macOS , and Linux .

This tutorial showed you how to export shell variables in Linux using the bash export command. If you deal with bash commands regularly, read how to write a bash script with examples and learn how to automate bash command execution.

bash export vs variable assignment

How-To Geek

How to work with variables in bash.

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

Hannah Stryker / How-To Geek

Quick Links

What is a variable in bash, examples of bash variables, how to use bash variables in scripts, how to use command line parameters in scripts, working with special variables, environment variables, how to export variables, how to quote variables, echo is your friend, key takeaways.

  • Variables are named symbols representing strings or numeric values. They are treated as their value when used in commands and expressions.
  • Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters.
  • Variables can be used to store and reference values. The value of a variable can be changed, and it can be referenced by using the dollar sign $ before the variable name.

Variables are vital if you want to write scripts and understand what that code you're about to cut and paste from the web will do to your Linux computer. We'll get you started!

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

Here, we'll create five variables. The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

We'll create four string variables and one numeric variable,

my_name=Dave

my_boost=Linux

his_boost=Spinach

this_year=2019

Defining variables in Linux.

To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

echo $my_name

echo $my_boost

echo $this_year

Using echo to display the values held in variables in a terminal window

Let's use all of our variables at once:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminal window

The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost , you just repeat what you did when you assigned its first value, like so:

my_boost=Tequila

my_boost=Tequila in a terminal window

If you re-run the previous command, you now get a different result:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminalwindow

So, you can use the same command that references the same variables and get different results if you change the values held in the variables.

We'll talk about quoting variables later. For now, here are some things to remember:

  • A variable in single quotes ' is treated as a literal string, and not as a variable.
  • Variables in quotation marks " are treated as variables.
  • To get the value held in a variable, you have to provide the dollar sign $ .
  • A variable without the dollar sign $ only provides the name of the variable.

Correct an incorrect examples of referencing variables in a terminal window

You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

drink_of-the_Year="$my_boost $this_year" in a terminal window

Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution. To illustrate the difference, here's a script that counts the files in the /dev directory.

Type this into a text file, and then save it as fcnt.sh (for "file count"):

#!/bin/bashfolder_to_count=/devfile_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

Before you can run the script, you have to make it executable, as shown below:

chmod +x fcnt.sh

chmod +x fcnt.sh in a terminal window

Type the following to run the script:

./fcnt.sh in a terminal window

This prints the number of files in the /dev directory. Here's how it works:

  • A variable called folder_to_count is defined, and it's set to hold the string "/dev."
  • Another variable, called file_count , is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ) . Note there's a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it's passed a value to hold; it isn't concerned with how the value was obtained.
  • The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to "/dev." So, the script executes the command "ls /dev."
  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the "/dev" directory. This value is assigned to the file_count variable.
  • The final line uses echo to output the result.

But this only works for the "/dev" directory. How can we make the script work with any directory? All it takes is one small change.

Many commands, such as ls and wc , take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files , you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

Our scripts can accept command line parameters. They're referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there's a $0 , as well, but that's reserved to always hold the script.)

You can reference command line parameters in a script just as you would regular variables. Let's modify our script, as shown below, and save it with the new name fcnt2.sh :

#!/bin/bashfolder_to_count=$1file_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1 .

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it's not hardcoded to work only with "/dev."

Here's how you make the script executable:

chmod +x fcnt2.sh

chmod +x fcnt2.sh in a terminal window

Now, try it with a few directories. You can do "/dev" first to make sure you get the same result as before. Type the following:

./fnct2.sh /dev

./fnct2.sh /etc

./fnct2.sh /bin

./fnct2.sh /dev in a terminal window

You get the same result (207 files) as before for the "/dev" directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

To shorten the script, you could dispense with the variable, folder_to_count , altogether, and just reference $1 throughout, as follows:

#!/bin/bash file_count=$(ls $1 wc -l) echo $file_count files in $1

We mentioned $0 , which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it's renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

The following are the other special preset variables:

  • $# : How many command line parameters were passed to the script.
  • $@ : All the command line parameters passed to the script.
  • $? : The exit status of the last process to run.
  • $$ : The Process ID (PID) of the current script.
  • $USER : The username of the user executing the script.
  • $HOSTNAME : The hostname of the computer running the script.
  • $SECONDS : The number of seconds the script has been running for.
  • $RANDOM : Returns a random number.
  • $LINENO : Returns the current line number of the script.

You want to see all of them in one script, don't you? You can! Save the following as a text file called, special.sh :

#!/bin/bashecho "There were $# command line parameters"echo "They are: $@"echo "Parameter 1 is: $1"echo "The script is called: $0"# any old process so that we can report on the exit statuspwdecho "pwd returned $?"echo "This script has Process ID $$"echo "The script was started by $USER"echo "It is running on $HOSTNAME"sleep 3echo "It has been running for $SECONDS seconds"echo "Random number: $RANDOM"echo "This is line number $LINENO of the script"

Type the following to make it executable:

chmod +x special.sh

fig13 in a terminal window

Now, you can run it with a bunch of different command line parameters, as shown below.

./special.sh alpha bravo charlie 56 2048 Thursday in a terminal window

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

To see the active environment variables in your Bash session, use this command:

env | less in a terminal window

If you scroll through the list, you might find some that would be useful to reference in your scripts.

List of environment variables in less in a terminal window

When a script runs, it's in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We'll show you how to this with two scripts.

First, save the following with the filename script_one.sh :

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./script_two.sh# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var , and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh . When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

The second script we'll use is script_two.sh . This is the script that script_one.sh calls. Type the following:

#!/bin/bash# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"# set new valuesfirst_var=charliesecond_var=delta# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

To run these scripts, you have to type the following to make them executable:

chmod +x script_one.shchmod +x script_two.sh

chmod +x script_one.sh in a terminal window

And now, type the following to launch script_one.sh :

./script_one.sh

./script_one.sh in a terminal window

This is what the output tells us:

  • script_one.sh prints the values of the variables, which are alpha and bravo.
  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.
  • script_two.sh changes them to charlie and delta.
  • script_one.sh prints the values of the variables, which are still alpha and bravo.

What happens in the second script, stays in the second script. It's like copies of the variables are sent to the second script, but they're discarded when that script exits. The original variables in the first script aren't altered by anything that happens to the copies of them in the second.

You might have noticed that when scripts reference variables, they're in quotation marks " . This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

Here's an example:

site_name=How-To Geek

site_name=How-To Geek in a terminal window

Bash sees the space before "Geek" as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing — not even the "How-To" text.

Try that again with quotation marks around the value, as shown below:

site_name="How-To Geek"

site_name="How-To Geek" in a terminal window

This time, it's recognized as a single value and assigned correctly to the site_name variable.

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what's going to happen is what you want. You can also catch any mistakes you might have made in the syntax.

Linux Commands

Files

Processes

Networking

  • Linux & macOS Terminal

The Linux Code

Demystifying Exporting Variables in Bash

So you want to learn the insider secrets of exporting variables in Bash? Well friend, you‘ve come to the right place!

Exporting variables is an essential skill for any Linux user looking to write effective Bash scripts and master the command line. But there‘s a lot of confusion around this topic.

By the end of this guide, you‘ll have a deep understanding of exporting Bash variables. You‘ll level up your scripting skills and impress your coder friends with your Linux fu!

Why Learn About Exporting Variables?

Before we dive in, let‘s quickly cover why learning about exporting variables matters:

  • Shell scripting power – Bash is the most widely used shell scripting language. Exporting variables unlocks more advanced scripting capabilities.
  • Programmer productivity – Variables make scripts more organized and reusable. Exporting them expands that productivity gain.
  • Admin magic – Sysadmins rely on exporting variables to configure servers and write automated management scripts.
  • Flex your Linux muscles – Mastering Bash is a rite of passage for Linux geeks. Exporting variables is an essential milestone.

So in summary, learning Bash variable exporting gives you more Linux street cred and unlocks next-level shell scripting mastery. Let‘s do this!

A Quick Bash Refresher

Before jumping into variables, let‘s recap what exactly Bash is for those who may be newer to Linux:

  • Bash stands for Bourne Again SHell . It‘s a pun on the name of the classic Bourne shell that Bash extends.
  • Bash is the default shell on most modern Linux distributions and macOS. The shell provides the user interface for typing commands.
  • Bash is also a scripting language used to automate tasks and write programs on Linux/Unix systems. Scripts are text files running collections of commands.

Some fun facts about Bash adoption:

Statistic Value
Most common Linux user shell
Default shell on Linux Yes, on most distros like Ubuntu
Default on macOS Yes
Total installations Estimated at

As you can see, Bash is massively popular – so it‘s worth taking the time to master it!

Introduction to Variables in Bash

Now that we‘ve got the Bash basics down, let‘s look at variables.

Variables are named containers used to store data. They are at the core of any programming language.

In Bash, variables:

  • Can store strings , numbers , single characters , or lists of data
  • Are accessed by putting a $ before the variable name – e.g. $my_var
  • Are created on first assignment – no declaration needed

Let‘s look at a simple example:

We simply assigned a value to my_var to create the variable. Then we can access it using $my_var .

You‘ll also see common naming conventions like:

  • lower_case_names – for script local variables
  • ALL_CAPS_NAMES – for global environment variables

With the basics down, let‘s move on to the good stuff – exporting!

Exporting Variables for Access Across Scripts

Exporting a variable makes it accessible across multiple scripts and processes. This converts a regular variable into an "environment variable".

Exporting is straightforward – just use the export builtin command:

Now my_var is an environment variable accessible by any child process:

The child script script.sh can access the exported my_var .

Some key facts about exported environment variables:

  • Exported vars are available to child processes/scripts
  • Changes in parent do not propagate to children
  • Can only be accessed by name – no references
  • Make read-only where possible as good practice

Exporting is a one-way street – children get a copy of the parent variables. But updates in the parent are not seen by children.

Now let‘s go deeper and see how exporting affects variable scoping…

Variable Scope 101

Scope refers to where a variable is accessible. Bash has local variables and global variables.

By default, variables are local in scope:

  • Local – Exists only within the script, function or block where defined
  • Global – Available throughout the entire script

For example:

The local keyword makes my_var local to my_func .

Exporting converts a global variable to an environment variable, available across the whole system:

  • Environment – Exists outside of the current script, available externally

This distinction is important when exporting – you are promoting a global variable to environment visibility.

A Tale of Two Scopes

To demonstrate local vs global vs environment variables, consider this example:

This shows the progression from local to global to exported environment variable.

Here is a summary of the key variable scope rules in Bash:

Scope Definition Access
Local Exists within function/script defined Only inside function/script
Global Exists for all of script Available to whole script (but not child processes)
Environment Export using Available externally across system

So in review, exporting promotes a global variable to be an environment variable.

A Practical Example

Understanding scoping rules is essential when deciding whether to export a variable.

Here is a common example – setting a script configuration variable:

By exporting MY_CONFIG , the main script can use it. This keeps the configuration cleanly separated from the script logic.

Some other examples where exporting variables is useful:

  • Defining startup environment and defaults in .bashrc
  • Sharing state between scripts like counters
  • Passing database credentials to scripts
  • Setting API keys or access tokens for scripts to use
  • Configuring system-wide states like install prefixes

So in summary, exporting gives global script variables broader reach.

Exporting Variables Persistently

Variables exported in a script are available only for that script session. Once the shell process exits, those exports are discarded.

To persist exported variables across shell sessions, place them in Bash profile scripts like:

  • ~/.bash_profile – Loaded on login for interactive non-login shells
  • ~/.bashrc – Loaded for interactive non-login shells
  • /etc/profile – Loaded on login for all users

This persists MY_EDITOR and customizes MY_PROMPT on every new shell.

Similarly, exported vars can be configured system-wide by adding them to files like /etc/environment .

Potential Pitfalls of Exporting

Exporting variables is powerful but also comes with some tradeoffs to keep in mind:

  • Changes in parent don‘t propagate to children automatically
  • Can override unexpectedly if local and global variable of same name
  • Inherits references, not values – can cause surprises
  • Leaked secrets and keys if not careful

Best practices when exporting:

  • Avoid complex data types – strings and numbers are ideal
  • Make read-only where possible
  • Namespace variables wisely to avoid conflicts
  • Don‘t export sensitive credentials

So in summary, exporting can have side-effects so be careful in using it.

Tips for Exporting Variables Like a Pro

If you follow these pro tips when exporting Bash variables, you‘ll avoid issues down the road:

  • Start small – Declare as local and only export once tested
  • Use namespaces – Prefix variables like MY_VAR to avoid conflicts
  • Export readonly – Add readonly modifier if variable shouldn‘t change
  • Check for existing – Avoid overwriting existing environment variables
  • Unset with care – Unsetting exported variables impacts other processes

And of course, document exported variables clearly in scripts!

Alternative Ways to Export Variables

Exporting with the export builtin is the standard approach. But there are some alternative options:

  • declare -x – Set + export in one step declare -x MY_VAR="hello"
  • Assign to well-known file like ~/.bashrc – Loaded on shell startup
  • source a file with exports from scripts # config.sh MY_VAR="value" # Main script source ./config.sh echo $MY_VAR

So in summary, the export command is preferred but not the only approach.

Related Shell Commands

Beyond export itself, there are some other handy Bash shell commands that relate to exported variables:

  • printenv – Print all exported environment variables
  • env – List all environment variables
  • export -p – List variables exported in current shell
  • export -n VAR – Unset an environment variable

These help inspect what variables are exported vs local only.

Recapping Variable Exporting Best Practices

Let‘s recap the key best practices around exporting variables in Bash:

  • Export variables to promote global script vars to environment
  • Understand scope rules – local vs global vs environment
  • Avoid unintentional overwriting with namespacing
  • Prefer read-only exports where possible
  • Persist exports in .bashrc or profiles for permanent availability
  • Take care not to leak secrets or credentials
  • Use export , declare -x , or source files to export
  • Document exported vars clearly

Following these tips will make you a variable exporting expert!

Phew – we covered a lot of ground here! Let‘s quickly recap:

  • Exporting variables promotes visibility across Bash environment
  • It converts global script variables to environmental variables
  • Scope rules determine if variable is local vs global vs external
  • Exporting copies value into child processes
  • Changes in parent don‘t flow down automatically
  • Use export or declare -x to export variables
  • Export in profiles to persist across sessions

In summary, exporting is powerful but needs some care. Use it judiciously and you‘ll write more robust Bash scripts in no time!

I hope this guide shed some light demystifying variable exporting in Bash. Mastering this will take your shell scripting skills to the next level.

Now go dazzle your colleagues with your Linux wisdom!

You maybe like,

Related posts, 10 awesome awk command examples for text processing.

Awk is an extremely useful command line tool for processing text data in Linux and Unix systems. It allows you to extract columns, filter lines,…

20 Practical Awk Examples for Beginners

Awk is a powerful programming language for text processing and generating reports on Linux systems. With awk, you can perform filtering, transformation, and reporting on…

25 Essential Bash Commands for Beginners

The bash shell is the default command-line interface for most Linux distributions and Apple‘s macOS. Mastering basic bash commands allows you to efficiently interact with…

3 Hour Bash Tutorial

(expanded 2500+ word article goes here…)

30 Bash Loop Examples to Improve Your Coding Skills

Loops allow you to automate repetitive tasks and are an essential part of any programming language. Bash scripting is no exception. Bash supports three types…

30 Bash Script Examples for Beginners

Bash scripting is an essential skill for Linux system administrators and power users. This comprehensive guide provides over 30 bash script examples for practical tasks…

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Difference between "a=b" and "export a=b" in bash

What's the difference between:

I understand that they both define environment variables, but I don't fully understand the difference.

  • environment-variables

Kenny Evitt's user avatar

  • Could somebody please edit this? This is not at all related to Linux, but depend only on the shell you are using. I guess it's bash here, which also works on Windows. –  innaM Commented Aug 6, 2009 at 12:52
  • I stand corrected. –  Adam Matan Commented Aug 6, 2009 at 12:58
  • export a=b only means that you get an variabel with the name 'a' and value 'b'. –  Stefan Skoglund Commented May 2, 2020 at 16:28
  • Related: Stack Overflow: Unix: What is the difference between source and export? –  Gabriel Staples Commented Mar 9, 2023 at 2:34

4 Answers 4

export propagates the variable to subprocesses.

For example, if you did

then a subprocess that checked for FOO wouldn't find the variable whereas

would allow the subprocess to find it.

But if FOO has already been defined as an environment variable, then FOO=bar will modify the value of that environment variable.

For example:

Older shells didn't support the export FOO=bar syntax; you had to write FOO=bar; export FOO .

Keith Thompson's user avatar

  • 59 Actually, if you don't use " export ", you're not defining an environment variable, but just a shell variable. Shell variables are only available to the shell process; environment variables are available to any subsequent process, not just shells. In addition, subshells are commands contained within parentheses, which do have access to shell variables, whereas what you're talking about are child processes that happen to be shells. –  wfaulk Commented Sep 28, 2009 at 12:02
  • 1 Where are these stored? –  Dave Commented Mar 18, 2013 at 21:45
  • 4 What's a "subprocess"? What are some common examples of subprocesses? –  littleO Commented May 23, 2020 at 7:38

If you don't use export , you're not defining an environment variable; just a shell variable.

Shell variables are only available to the shell process; environment variables are available to any subsequent process, not just shells.

wfaulk's user avatar

Also, if you want to have the variable available to the calling shell without using export you can do this:

File a.ksh is -

On the prompt, run this is

This will run the commands within the same shell and $FOO will be available.

Will make $FOO available only within a.ksh, after the call to a.ksh it would not exist.

alok's user avatar

  • 2 Correct. Note that "." is just a shortcut for "source", which is sometimes used in scripts for better readability. See "help ." or "help source" for details. –  sleske Commented Feb 11, 2010 at 22:58

In addition to what has already been answered, both of these statement do not necessarily define (i.e. create vs set) an environment variable as "a" might already exist as a shell or environment variable.

In the latter case, both statements are strictly equivalent.

jlliagre's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged bash shell process environment-variables ..

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities

Hot Network Questions

  • Convert base-10 to base-0.1
  • What does "either" refer to in "We don't have to run to phone booths anymore, either"?
  • Why is the Liar a problem?
  • Boon of combat prowess when you can only attack once
  • Why did the Chinese government call its actual languages 'dialects'? Is this to prevent any subnational separatism?
  • Build exterior cabin walls using plywood siding
  • Will a recent B2 travel to the same location as my F1 college application affect the decision
  • How Can I Modify a C Program to Gain Root Shell Access Without Using Sudo or Editing the Sudoers File?
  • Fill this Sudoku variant so that the sums of numbers in the outlined regions are all different
  • Finding specific promotions from two columns
  • Seeking an explanation for the change in order of widening operations from .NET Framework 4.8 to .NET 8
  • How to see material properties (colors) in main view
  • How to make a soundless world
  • Can All Truths Be Scientifically Verified?
  • Fifth year PhD student with no progress on my thesis because of advisor, what to do?
  • Modifying Expansion Order with \seq put right
  • Could a Gamma Ray Burst knock a Space Mirror out of orbit?
  • how to rotate only closest element to body?
  • Inverses of Morphisms Necessarily Being Morphisms
  • Which cartoon episode has Green Lantern hitting Superman with a tennis racket and sending him flying?
  • Stretched space in math mode
  • Driving low power LEDs from pre-biased digital transistors
  • crontab schedule on Alpine Linux runs on days it's not supposed to run on
  • how does the US justice system combat rights violations that happen when bad practices are given a new name to avoid old rulings?

bash export vs variable assignment

How to Export Variables From a File

Last updated: March 18, 2024

bash export vs variable assignment

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

1. Overview

Exporting variables from a file is a common task for loading specific configurations or credentials. By exporting variables, configurations can be inherited by child processes and subshells.

In this tutorial, we’ll explore different ways to export variables from a file in Bash.

2. Sample Task

Let’s suppose we have a configuration file named .env :

The file contains three variables, a , b , and c that we wish to export. In addition, it contains a blank line and a fourth variable, d , on a line that is commented out . Notably, we see that comments can follow variable declarations on the same line.

Our goal is to export all the variables in the file which aren’t commented out .

Let’s explore different methods to accomplish this task.

3. Exporting Variables by Sourcing a File

One approach to exporting variables from a file involves sourcing the file to load the variables into the current environment. We can either enable a special shell option for exporting variables and then source the file, or we can first source the file and then use the export command over the variables to be exported .

3.1. Using set -a

Perhaps the simplest approach to exporting variables from a file is to first enable the allexport shell option via set -a and then source the file :

At this point, by sourcing the .env file, the a , b , and c variables become available in the current environment and are also exported due to the allexport option. Finally, we reset the allexport option using set +a .

We can also view the exported variables using the export command with the -p option:

We see that the a , b , and c variables are among those exported.

3.2. Using export With sed and cut

Another approach is to first source the configuration file and then use the export command over the list of variables . To extract the list of variables, we can use sed and cut :

First, we use sed to delete lines that begin with a hash symbol preceded by zero or more whitespace characters since such lines represent comments. Using sed , we also delete lines that contain only zero or more whitespace characters as we consider these as blank lines. The -E option used with sed enables extended regex .

Then, we pipe the result from sed to the cut command to extract the variable names that precede an equal sign. We use the -d option with cut to set the delimiter to an equal sign and the -f option to specify the field number we wish to extract.

Therefore, we can now source the .env file and export the variables :

Notably, we use sed and cut within a command substitution to list the variable names. We also use the && logical operator to run the export command over the list of variables once we’ve successfully sourced the .env file.

3.3. Using export With grep and cut

Alternatively, we can use grep instead of sed :

We use the -E option with grep to enable extended regex and the -v option to exclude the specified pattern. Similar to the sed case, the pattern we exclude consists of either a hash symbol preceded by zero or more whitespace characters, or blank lines containing zero or more whitespace characters.

The solution is then similar in construct to the one used with sed :

In summary, we first source the .env file, and then we export the variables after extracting their names via grep and cut .

4. Exporting Variables Without Sourcing a File

Another approach to exporting variables from a file is by using the export command directly over the variable declarations, without sourcing the file :

The export_variables.sh script performs several steps:

  • use a while loop along with the read command to read the lines of the .env file, one by one, into a variable named line
  • use the ${line%%#*} parameter expansion expression to remove hash symbols and all subsequent characters from each line
  • echo the result of the parameter expansion and pipe the output to xargs to remove any leading or trailing whitespace characters
  • use the test builtin with the -n option to check if the resulting line variable is non-empty, and if so, export it

Let’s grant the script execute permissions via chmod :

Finally, let’s unset the variables and source the script:

We can check the exported variables:

Consequently, we see that the three variables, a , b , and c were exported.

5. Conclusion

In this article, we explored different ways to export variables from a file in Bash.

One approach involved using set -a and then sourcing the file. Another approach required first sourcing the file and then exporting the variables via the export command. In that approach, we extracted the variable names using cut in conjunction with either sed or grep . Finally, a final method was to use a while loop to read and process the lines of the file and then export only valid lines that represent variable declarations.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Why not to export variables on the same line you assign them?

From What is the last argument of the previous command?

shellcheck tells you not to export variables on the same line you assign them.

I was wondering why?

Does the same advice apply to alias , declare , export , local , readonly , and typeset ?

Braiam's user avatar

  • 1 See also Why is it not required to double quote `$bar` in assignment `foo=$bar`? –  Stéphane Chazelas Commented Apr 17, 2018 at 10:41
  • 1 And Are quotes needed for local variable assignment? –  Stéphane Chazelas Commented Apr 17, 2018 at 10:43
  • 9 The shellcheck rule in question is SC2155. There is pretty good documentation at the shellcheck wiki . –  phunehehe Commented Apr 17, 2018 at 12:19
  • 3 Also some older shells wouldn't accept export and assignment together. The Heirloom Bourne Shell , for example, outputs a "foo=2 is not an identifier" error. –  Dennis Williamson Commented Apr 17, 2018 at 21:12

The problem is that in Bash every command has only one exit code. When you export foo="$(false)" the exit code of false is simply discarded. If you instead do

the failing first command can be acted upon, for example by the errexit setting.

Declaring and assigning a string literal such as export foo='bar' does of course not suffer from this problem. But change is the only constant in software development, and it's simply good housekeeping to future-proof such statements by splitting them up.

In addition to the assignment specific commands you mention there's also multiple commands in a single assignment such as foo="$(false)$(true)" . See pipefail in man bash for yet another such trap.

Another thing to remember is that the sequence of declaration and assignment is sometimes relevant. For example, you'll want to declare variables local before assigning them. (Unfortunately it's not possible to declare variables readonly before assigning them for the first time.)

Cristian Ciupitu's user avatar

  • So if one is setting a variable from a literal, and there's no exit code to discard, there's nothing wrong with doing it all on one line. –  Monty Harder Commented Apr 17, 2018 at 17:59
  • 1 As far as this shellcheck error is concerned, no. But as now-deleted answers got half-right between them, the Bourne shell did not support the assignment syntax for export , so for some years there was received wisdom about doing this if one's interpreter was likely to be the Bourne shell. –  JdeBP Commented Apr 17, 2018 at 18:53
  • @JdeBP, note that the Bourne shell did support foo=$(cmd) export foo , though with the same caveat that cmd 's exit status is lost (but did cause the shell to exit if failing with set -e ). –  Stéphane Chazelas Commented Apr 18, 2018 at 14:40
  • That was covered by my first sentence. –  JdeBP Commented Apr 19, 2018 at 5:16

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged bash ..

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities

Hot Network Questions

  • Does the different strength of gravity at varying heights affect the forces within a suspended or standing object
  • What's the strongest material known to humanity that we could use to make Powered Armor Plates?
  • How does 「交換したていで」 mean "say you changed [the oil]"?
  • Counting the number of meetings
  • HTA w/ VBScript to open and copy links
  • What is an apologetic to confront Schellenberg's non-resistant divine hiddenness argument?
  • Why doesn't Wolfram Alpha give me the correct answer for this?
  • Symbolic integral over real functions with interger parametres evaluates to complex numbers
  • Are these colored sets closed under multiplication?
  • One-line negative review
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • A coworker says I’m being rude—only to him. How should I handle this?
  • Fantasy novel where a brother and sister go to a fantasy and travel with a one-armed warrior
  • Missed the application deadline for a TA job. Should I contact them?
  • How to win a teaching award?
  • Movie from the fifties where aliens look human but wear sunglasses to hide that they have no irises (color) in their eyes - only whites!
  • Convert base-10 to base-0.1
  • I have been trying to solve this Gaussian integral, which comes up during the perturbation theory
  • Reparing a failed joint under tension
  • Bitcoin Core 28 Tests (testmempoolaccept rejected but submitpackage accepted)
  • how does the US justice system combat rights violations that happen when bad practices are given a new name to avoid old rulings?
  • What do I NEED?
  • Alice splits the bill not too generously with Bob
  • Is internal energy depended on the acceleration of the system?

bash export vs variable assignment

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Why separate declaration from export of variables in bash scripts?

I have a bash script like

They first declare the variable and set it to a value, then in a separate line, they export it. Personally, I like to just do it in one line like:

Is there some style rule against this? I've seen the declaration and export be separated by others, but never knew why.

If it helps, this script runs on Linux Mint, but could run on other Linux's or even a Mac.

wjandrea's user avatar

  • 1 From what I know, separating them makes it POSIX compatible –  Fravadona Commented Jan 6, 2022 at 18:36
  • Since you're using Bash don't worry about it. –  konsolebox Commented Jan 6, 2022 at 18:42
  • 3 @Fravadona POSIX allows assignments in export commands. Some older shell may not have, which may have led to a belief that export must still be done separately from assignment. –  chepner Commented Jan 6, 2022 at 18:51
  • A lot of people also use export even when it isn't needed; I wouldn't take a random sample of bash scripts in the wild as indicative of anything resembling good practice. –  chepner Commented Jan 6, 2022 at 18:53
  • @chepner Thanks for correcting a misconception of mine. I came up with this conclusion by looking at the default ~/.profile and ~/.bash_profile in some Linux distros –  Fravadona Commented Jan 6, 2022 at 19:09

Because export is a command; when assignment comes from a command or sub-shell output, its own return code will override/mask the return code of the assigning command:

Léa Gris's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged bash or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Smoking on a hotel room's balcony in Greece
  • Would a scientific theory of everything be falsifiable?
  • Stretched space in math mode
  • Modifying Expansion Order with \seq put right
  • Does the city of Springfield have a possible claim against the Trump/Vance campaign?
  • how to rotate only closest element to body?
  • Water got on electric circuits, new breakers for circuits does not fix them
  • Alice splits the bill not too generously with Bob
  • Why is the Liar a problem?
  • Smallest root of a degree 3 polynomial
  • A coworker says I’m being rude—only to him. How should I handle this?
  • What makes amplifiers so expensive?
  • HTA w/ VBScript to open and copy links
  • Are these colored sets closed under multiplication?
  • Seeking an explanation for the change in order of widening operations from .NET Framework 4.8 to .NET 8
  • Does the different strength of gravity at varying heights affect the forces within a suspended or standing object
  • Reparing a failed joint under tension
  • how does the US justice system combat rights violations that happen when bad practices are given a new name to avoid old rulings?
  • How to plug a frame hole used for a rear mechanical derailleur?
  • Has Macron's new government indicated whether it is "leaning" hard left or hard right?
  • Can noun phrase have only one word?
  • "00000000000000"
  • Is it possible/recommended to paint the side of piano's keys?
  • Coloring a function based on its monotonicity

bash export vs variable assignment

IMAGES

  1. bash script export environment variable

    bash export vs variable assignment

  2. Bash Scripts Set Environmental Variables with EXPORT [HowTo]

    bash export vs variable assignment

  3. Bash Export Command: Everything You Need To Know

    bash export vs variable assignment

  4. Difference Between Defining Bash Variables With And Without export

    bash export vs variable assignment

  5. Bash Export Variable {With Examples}

    bash export vs variable assignment

  6. Bash Export Variable

    bash export vs variable assignment

VIDEO

  1. Working with BASH shell

  2. shell vs environment variables (and env, export, etc.) (intermediate) anthony explains #547

  3. Intermediate Bash Scripting Tutorial: How to Pass and Reference Arguments in Functions

  4. iDempiere 3.1 Installation in Linux (Ubuntu / Elementary OS)

  5. EPC Export Summit 2024

  6. How to get values for variables from a source file using Bash Script on Rocky Linux 9.2

COMMENTS

  1. Defining a Bash Variable With or Without 'export'

    2. With export vs. Without export. Bash variables are very handy, just like variables in other programming languages, such as Java or C++. One major difference though is that they don't need declaration; just assigning a value to the variable name creates a variable: $ MYVAR=1729 $ export MYVAR=1729.

  2. Defining a variable with or without export

    It should be noted that you can export a variable and later change the value. The variable's changed value will be available to child processes. Once export has been set for a variable you must do export -n <var> to remove the property. $ K=1 $ export K $ K=2 $ bash -c 'echo ${K-unset}' 2 $ export -n K $ bash -c 'echo ${K-unset}' unset

  3. bash

    export: makes shell variables environment variables; In short: set doesn't set shell nor environment variables; env can set environment variables for a single command; declare sets shell variables; export makes shell variables environment variables; NOTE declare -x VAR=VAL creates the shell variable and also exports it, making it environment ...

  4. What's the Difference Between Bash's set and export ...

    We can use export to set environment variables in files such as ~/.bashrc or /etc/profile. The shell sources these files when it starts or when we log in. For example, we can use export LANG=en_US.UTF-8 in /etc/profile to set the default language and encoding for all users. 4. Differences Between set and export.

  5. How to Defining a Bash Variable With or Without 'export' in Linux

    So the variables exported from the script are only used in the subshell, not the parent shell. Step 1: You can easily create a file to store your script ("outscript.sh") with the following command: echo "export message='Hello from GeeksForGeeks'" > outscript.sh. Step 2: With the help of "chmod +x", we can load "outscript.sh" into ...

  6. command line

    Exporting a variable causes the variable to be inherited: export GREP_OPTIONS='-v' grep one test.txt returns now. line two This is the most common way of setting variables for use of subsequently started processes in a shell. This was all done in bash. export is a bash builtin; VAR=whatever is bash syntax. env, on another hand, is a program in ...

  7. Exporting Variables in Bash: the Why and How

    bash. echo ${C} echo ${D} In this example we see that the D variable retains it's export property, even when re-assigned without the explicit export command, and it's value is correctly passed to the subshell. The export property can also be removed from/turned off for a variable, by using the -n option to export.

  8. Bash Export Variable {With Examples}

    How to Export Bash Variable. The syntax for the export command is simple: export [variable-name] The example below confirms that the test variable exists even after using bash to start a new shell session. The scripts now also have access to the variable. Execute the previously created script again. ./test-script.sh.

  9. How to Work with Variables in Bash

    Here, we'll create five variables. The format is to type the name, the equals sign =, and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable. We'll create four string variables and one numeric variable, my_name=Dave.

  10. Demystifying Exporting Variables in Bash

    This converts a regular variable into an "environment variable". Exporting is straightforward - just use the export builtin command: # Assign to regular var. my_var="value". # Export it. export my_var. Now my_var is an environment variable accessible by any child process: # Export the variable. export my_var="value".

  11. Difference between shell variables which are exported and those which

    From the export man page: The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. set outputs the current environment, which includes any local non-exported variables.

  12. Difference between "a=b" and "export a=b" in bash

    93. export propagates the variable to subprocesses. For example, if you did. FOO=bar. then a subprocess that checked for FOO wouldn't find the variable whereas. export FOO=bar. would allow the subprocess to find it. But if FOO has already been defined as an environment variable, then FOO=bar will modify the value of that environment variable.

  13. How to Export Variables From a File

    Perhaps the simplest approach to exporting variables from a file is to first enable the allexport shell option via set -a and then source the file: $ set -a. $ . . env. $ set +a. Copy. At this point, by sourcing the .env file, the a, b, and c variables become available in the current environment and are also exported due to the allexport option.

  14. What is the difference between source and export?

    When you source the file, the assignments will be set but the variables are not exported unless the allexport option has been set. If you want all the variables to be exported, it is much simpler to use allexport and source the file than it is to read the file and use export explicitly. In other words, you should do: set -a . file.txt (I prefer . because it is more portable than source, but ...

  15. shell

    In order to export out the VAR variable first, the most logical and seemly working way is to source the variable:. ./export.bash or. source ./export.bash

  16. In Bash, should I use declare instead of local and export?

    The shell has forced the assignment to be treated as a integer expression instead of a plain variable assignment. The export/local commands don't define this special processing to be applied to assignments. Also the built-ins local/export were added to bash much earlier than the attributes which declare provides.

  17. Why not to export variables on the same line you assign them?

    56. The problem is that in Bash every command has only one exit code. When you export foo="$(false)" the exit code of false is simply discarded. If you instead do. foo="$(false)" export foo. the failing first command can be acted upon, for example by the errexit setting. Declaring and assigning a string literal such as export foo='bar' does of ...

  18. Why separate declaration from export of variables in bash scripts

    5. Because export is a command; when assignment comes from a command or sub-shell output, its own return code will override/mask the return code of the assigning command: # the return-code of the getDBName function call. # is masked by the export command/statement. export DATABASE_NAME=$(getDBName) # Separate export. export DATABASE_NAME.