To set variable only for current shell:

VARNAME="my value"

To set it for current shell and all processes started from current shell:

export VARNAME="my value"      # shorter, less portable version

To set it permanently for all future bash sessions add such line to your .bashrc file in your $HOME directory.

To set it permanently, and system wide (all users, all processes) add set variable in /etc/environment:

sudo -H gedit /etc/environment

This file only accepts variable assignments like:

VARNAME="my value"

Do not use the export keyword here.

Use source ~/.bashrc in your terminal for the changes to take place immediately.

Answer from Michał Šrajer on askubuntu.com
Top answer
1 of 5
454

This is because the shell expands the variable in the command line before it actually runs the command and at that time the variable doesn't exist. If you use

TEST=foo; echo $TEST

it will work.

export will make the variable appear in the environment of subsequently executed commands (for on how this works in bash see help export). If you only need the variable to appear in the environment of one command, use what you have tried, i.e.:

TEST=foo your-application

The shell syntax describes this as being functionally equivalent to:

export TEST=foo
your-application
unset TEST

See the specification for details.

Interesting part is, that the export command switches the export flag for the variable name. Thus if you do:

unset TEST
export TEST
TEST="foo"

TEST will be exported even though it was not defined at the time when it was exported. However further unset should remove the export attribute from it.

2 of 5
92

I suspect you want to have shell variables to have a limited scope, rather than environment variables. Environment variables are a list of strings passed to commands when they are executed.

In

var=value echo whatever

You're passing the var=value string to the environment that echo receives. However, echo doesn't do anything with its environment list¹ and anyway in most shells, echo is built in and therefore not executed.

If you had written

var=value sh -c 'echo "$var"'

That would have been another matter. Here, we're passing var=value to the sh command, and sh does happen to use its environment. Shells convert each² of the variables they receive from their environment to a shell variable, so the var environment variable sh receives will be converted to a $var variable, and when it expands it in that echo command line, that will become echo value. Because the environment is by default inherited, echo will also receive var=value in its environment (or would if it were executed), but again, echo doesn't care about the environment.

Now, if as I suspect, what you want is to limit the scope of shell variables, there are several possible approaches.

Portably (Bourne and POSIX):

(var=value; echo "1: $var"); echo "2: $var"

The (...) above starts a sub-shell (a new shell process in most shells), so any variable declared there will only affect that sub-shell, so I'd expect the code above to output "1: value" and "2: " or "2: whatever-var-was-set-to-before".

With most Bourne-like shells (see List of shells that support `local` keyword for defining local variables), you can use functions and the "local" builtin:

f() {
  local var
  var=value
  echo "1: $var"
}
f
echo "2: $var"

With zsh, you can use anonymous functions which like normal functions can have a local scope:

(){ local var=value; echo "1: $var"; }; echo "2: $var"

or:

function { local var=value; echo "1: $var"; }; echo "2: $var"

With bash and zsh (but not ash, pdksh or AT&T ksh), this trick also works:

var=value eval 'echo "1: $var"'; echo "2: $var"

A variant that works in a few more shells (dash, mksh, yash) but not zsh (unless in sh/ksh emulation):

var=value command eval 'echo "1: $var"'; echo "2: $var"

(using command in front of a special builtin (here eval) in POSIX shells removes their specialness (here that variables assignments in front of them remain in effect after they have returned))

With the fish shell, you can make variables local to a begin..end block:

begin
  set -l var value
  echo 1: $var
end
echo 2: $var

With mksh (and soon zsh), you can abuse the ${|cmd} construct which can also have a local scope making sure it expands to nothing by making sure you don't set $REPLY within:

${|local var=value; echo "$var"}; echo "$var"

¹ Stricktly speaking, that's not completely true. Several implementations will care about the localisation environment variables (LANG, LOCPATH, LC_*...), the GNU implementation cares about the POSIXLY_CORRECT environment variable (compare env echo --version with env POSIXLY_CORRECT=1 echo --version on a GNU system).

² well only (some of) the ones that are valid variable names in the syntax of the particular shell. For instance env ++=foo 1x=bar 3=qwe '#=rty' IFS=asd é=x sh -c 'shell code' will not create ++, 1x, 3, # shell variables as those are not valid variable names (though # and 3 are non-variable shell parameters), and don't import IFS from the environment as that would be source of security vulnerabilities; for é, YMMV.

Discussions

Set environment variable for one command on command line
You use FOO=bar command just as you would in Bash. It’s not a “bashism”, it’s common for all Bourne-type shells. More on reddit.com
🌐 r/zsh
13
5
April 4, 2022
Setting an environment variable before a command in Bash is not working for the second command in a pipe - Stack Overflow
In a given shell, normally I'd set a variable or variables and then run a command. Recently I learned about the concept of prepending a variable definition to a command: FOO=bar somecommand someargs More on stackoverflow.com
🌐 stackoverflow.com
How can I set my environment variables permanently?
After every reboot and shutdown the environment variable should presist it value More on reddit.com
🌐 r/AskUbuntu
1
2
June 1, 2023
Would someone explain the environment variables like I'm a crayon eating five?
Think of environment variables like parameters that are automatically passed to every program you run. For example, instead of man --language=italian foo to get an Italian man page, you can have an environment variable that says your language is Italian (in actuality this would be the variable LANG=it_IT.utf8). Many environment variables (like the above LANG) are standardized, so that different applications can all use the same variable. And programs can ignore the ones they don't care about. Another more advanced use case is for securely passing parameters to programs. When you run foo --mypassword=abcd1234, anyone can run ps and see the arguments, and thus see your password. However if you set the password in an environment variable, only you can see it. Must know bit: How to set them is probably all there is to really know. When you set a variable in your shell by doing foo=bar, this isn't creating an environment variable. It's just create a variable (no "environment" part). To make it an environment variable, you have to export it. Such as by either doing two commands foo=bar; export foo or a single command export foo=bar. You can also set an environment variable for just a single instance of a program, and not have it persist. For example instead of doing: export foo=bar myprogram unset foo ... you can do foo=bar myprogram Lastly, when you set an environment variable, it doesn't live beyond the lifetime of the shell. So if you close your terminal and open a new one, the variable will be gone. If you want it to always be there, even when you launch a new shell, you'll need to set it in a rc/profile script (e.g. ~/.bashrc). More on reddit.com
🌐 r/linuxquestions
4
19
November 17, 2021
🌐
freeCodeCamp
freecodecamp.org › news › how-to-set-an-environment-variable-in-linux
How to Set an Environment Variable in Linux
October 26, 2022 - For the changes to take effect, use the command source /etc/environment. /etc/profile – Variables set in this file are read whenever a bash shell is logged in.
🌐
NTU Singapore
www3.ntu.edu.sg › home › ehchua › programming › howto › Environment_Variables.html
Environment Variables in Windows/macOS/Linux
Use "setenv varname value" and "unsetenv varname" to set and unset an environment variable. Use "set varname=value" and "unset varname" to set and unset a local variable for the current process. Most of the Unixes and macOS use the so-called Bash Shell in the "Terminal".
🌐
Reddit
reddit.com › r/zsh › set environment variable for one command on command line
r/zsh on Reddit: Set environment variable for one command on command line
April 4, 2022 -

I'm transitioning to zsh after many years of bash use and have almost got everything working. The one pattern I can't figure out is how to temporarily set/override an environment variable.

Bash allows:

The environment for any simple command or function may be
augmented temporarily by prefixing it with parameter assignments,
as described above in PARAMETERS.  These assignment statements
affect only the environment seen by that command.

I have scripts with lines of this form, where the value of FOO is set just for the single execution but seems not supported by zsh:

 FOO=bar command

A simple set/unset is fragile as any interruption of the contained command will forego the unset:

FOO=bar ; command ; unset FOO

The closest I've come is this, but I've not fully explored the implications of the subshell, especially related to traps:

(FOO=bar ; command)

I accept this may be an anti-pattern moving forward, but for now I'm just trying to get everything running again.

Find elsewhere
🌐
Launch School
launchschool.com › books › command_line › read › environment
How to Change your Command Line Environment
When you log in to the command line, a variety of environment variables are automatically set. You can see exactly what variables have been set, along with their values, by running env at the command line. Type env, hit enter, and find the value for HOME. It should say something like /home/ubuntu, ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-read-and-set-environmental-and-shell-variables-on-linux
How To Read and Set Environmental and Shell Variables on Linux | DigitalOcean
January 2, 2026 - Before diving into the details, here are the essential points about environment and shell variables on Linux: Environment variables are inherited by child processes and affect system-wide behavior, while shell variables are local to the current shell session · Use printenv or env to view environment variables, and set to see all shell and environment variables
🌐
ArchWiki
wiki.archlinux.org › title › Environment_variables
Environment variables - ArchWiki
3 weeks ago - This is not necessarily the currently running terminal (TERM). ... Contains the path to the web browser. Helpful to set in an interactive shell configuration file so that it may be dynamically altered depending on the availability of a graphic environment, such as X: [ -n "$DISPLAY" ] && export BROWSER=firefox || export BROWSER=links · Tip These default programs can also be set conditionally if a Wayland compositor is running by using the WAYLAND_DISPLAY environment variable...
🌐
Cherry Servers
cherryservers.com › home › blog › linux › how to list, set and manage linux environment variables
How to List, Set and Manage Linux Environment Variables | Cherry Servers
November 7, 2025 - ⚠️ Warning: Any shell on the system can access system-wide variables, so set them with caution. To set system-wide Linux environment variables, you can edit the /etc/environment file.
🌐
Linuxize
linuxize.com › home › bash › how to set environment variables in linux
How to Set Environment Variables in Linux | Linuxize
April 15, 2026 - ~/.bash_profile or ~/.profile - Loaded for login shells (when you log in via SSH or a console). This is where you should set environment variables that apply to your entire session. ~/.bashrc - Loaded for interactive non-login shells (when you open a new terminal window).
🌐
nixCraft
cyberciti.biz › nixcraft › howto › bash shell › how to set environment variables in linux
How to Set Environment Variables in Linux - nixCraft
February 8, 2023 - Open the terminal prompt and then type: $ printenv $ printenv VAR_NAME $ printenv PS1 $ printenv ORACLE_HOME $ printenv JAVA_HOME # use the grep command/egrep command to filter out variables # $ printenv | grep APP_HOME $ printenv | grep -E 'APP_HOME|DOCKER_HOME|NIX_BACKUP_HOST' The env command runs a Linux command with a modified environment. The syntax is: # Here is how to set env variable in linux using env command # $ env VAR_NAME=VALUE $ env VAR_NAME=VALUE CMD1 ARG1 $ env [options] VAR_NAME=VALUE CMD1 ARG1 Please note that if no command name is specified following the environment specifications, the resulting environment is displayed on screen.
🌐
PhoenixNAP
phoenixnap.com › home › kb › sysadmin › environment variables in linux: how to list, set, and manage
Environment Variables in Linux: How to List, Set, and Manage
December 10, 2025 - The sections below show how to create different types of environment variables in Linux. The simplest way to create a user environment variable is to type its name in the terminal, followed by its value.
🌐
Built In
builtin.com › software-engineering-perspectives › how-to-set-environment-variables-linux
How to Set Environment Variables in Linux | Built In
In this article, I will explain environment variables, why and when you want to use them and how to set them up. A tutorial of environment variables in Linux.
🌐
LinuxConfig
linuxconfig.org › home › how to set and list environment variables on linux
How to set and list environment variables on Linux
April 21, 2021 - Here’s how to create a new environment variable on Linux. Note that this is a temporary environment variable and won’t survive a system reboot, user logout, or new shell. As an example, we’ll create a new variable called MY_SITE. Use the following command to create a new shell variable. This will only make the variable active in your current session, but we will make an environment variable soon. ... Next, use the export command to set the new variable as an environment variable.
🌐
How-To Geek
howtogeek.com › home › linux › how to set environment variables in bash on linux
How to Set Environment Variables in Bash on Linux
December 6, 2023 - Learn how to view, create, and unset environment variables on Linux. We explain global, session, and shell variables.
Top answer
1 of 4
22

This is an excerpt from the Bash man page:

export [-fn] [name[=word]] ...
export -p
The supplied names are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the names refer to functions...

If you only need the variable in the current environment, it's not necessary to use export.

var=value

Edit:

Without export: current environment only. With export: current environment and child environments.

Here's a demonstration of the affect of export on availability of a variable in a child environment and that changes in the child environment don't affect the parent:

$ var1=123
$ export var2=456
$ echo "parent [$var1] [$var2] [$var3]"
parent [123] [456] []
$ var3=789 bash -c 'echo "child [$var1] [$var2] [$var3]"; var1=111; var2=222; var3=333; echo "child [$var1] [$var2] [$var3]"'
child [] [456] [789]
child [111] [222] [333]
$ echo "parent [$var1] [$var2] [$var3]"
parent [123] [456] []

After the first echo (echo "parent...") you see "123" and "456" because both var1 and var2 are active in the current environment. You don't see a value for var3 because it's not set yet.

After the line that starts "var3=..." you don't see a value for var1 because it wasn't exported. You do see a value for var2 because it was exported. You see a value for var3 because it was set for the child environment only.

(bash -c is equivalent to running a script with the contents of the argument to the -c option. A script or other executable or, in this case, the argument to bash -c becomes a child of the current environment which, as a result is, of course, the child's parent.)

In the "script" the values of the variable are changed. It now outputs those new values.

Once the "script" is finished, execution returns to the parent environment (the command line in this case). After the last echo, you see the original values because the changes made in the child environment do not affect the parent.

2 of 4
3

You say that

I am always using export command to set environment variable

By the way you worded that, it sounds like you are really trying to ask how do you make an environmental variable persists. To do that would require you to place your export VAR="foo" statement in your $HOME/.bash_profile file (if you are using bash). If you want that environmental variable to persist for all users but root, then add it to /etc/profile. If you want it added for the root user too, then set it in /root/.bash_profile .

This will work for all login shells where bash is the shell of choice. For non login shells, you need to use .bashrc. I have no insights to offer for other shells :D

🌐
Contabo
contabo.com › home › how to set and list environment variables in linux
How to Set and List Environment Variables in Linux | Contabo Blog
February 25, 2026 - These come pre-set on virtually every Linux distribution. You can define your own for any purpose: custom application configs, deployment flags, service endpoints. That’s where things get interesting. To print a single environment variable in Linux, use the echo command with a dollar sign prefix: ... The linux echo command reads the variable’s current value and writes it to the terminal.