Linux Set Environment Variable Command Tutorial

Bash shell is used for various purposes under Linux. How do I customize the shell environment variable under Linux operating systems? How can I set and view environment variable on Linux?

You can use shell variables to store data, set configuration options and customize the shell environment under Linux. The default shell is Bash under Linux and can be used for the following purposes:

  1. Configure look and feel of shell.
  2. Setup terminal settings depending on which terminal you’re using.
  3. Set the search path such as JAVA_HOME, and ORACLE_HOME.
  4. Create environment variables as needed by programs.
  5. Run commands that you want to run whenever you log in or log out.
  6. Set up aliases and/or shell function to automate tasks to save typing and time.
  7. Changing bash prompt.
  8. Setting shell options.

Two types of shell variables

  • Environment variables (GLOBAL): Typically, end-users shouldn’t mess with Environment variables as they are available system-wide, and subshells and child processes can access them. In certain scenarios, we can modify them as per our needs. For example, we set up a system-wide path for the JAVA app or PATH for searching binaries. In almost all cases, we use the export command to define or modify environment variables.
  • Shell and user-defined variables (LOCAL) : As the name suggests, these are defined by users and currently apply to the current shell session.

You can use the following commands to view and configure the environment.

Display current environment variables on Linux

The printenv command shows all or the given environment variables. Open the terminal prompt and then type:
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

env command

The env command runs a Linux command with a modified environment. The syntax is:

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. This is like specifying the printenv command as discussed earlier. For example:

env | more
env | grep 'PS1'

How to set and list environment variables in Linux using set command

The env command/printenv command displays only the Linux shell environment variables. What if you need to see a list of all variables, including shell, environment, user-defined shell functions? Try the following set command for printing environment variables:
set | grep BASH

Here is what we see:

BASH_VERSINFO=([0]="3" [1]="2" [2]="25" [3]="1" [4]="release" [5]="x86_64-redhat-linux-gnu")
IFS=$' \t\n'
LESSOPEN='|/usr/bin/ %s'
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "\007"'
PS1='[\u@\h \W]\$ '
PS2='> '
PS4='+ '
SSH_CLIENT=' 44212 22'
SSH_CONNECTION=' 44212 22'
genpasswd () 
    local l=$1;
    [ "$l" == "" ] && l=16;
    tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
xrpm () 
    [ "$1" != "" ] && ( rpm2cpio "$1" | cpio -idmv )

The $PATH defined the search path for commands. It is a colon-separated list of directories in which the shell looks for commands. The $PS1 defines your prompt settings. See the list of all commonly used shell variables for more information. You can display the value of a variable using the printf command or echo command:

echo "$HOME"
echo "$PS1"
printf "%s\n" "$HOME"

Outputs from the last command displaying my home directory location set by the $HOME environment variable on Linux:

Setting Environment Variables on Linux Command

The syntax is pretty simple:

# A variable may be assigned to by a statement of the form  #
VAR_STR="this is a string"
# If value is not given, the variable is assigned the null string.
# Empty variable 
# Boolean (true or false)

Some key points to remember when creating or setting up environment variables on Linux when using bash:

  1. Do not put space around the = symbol.
  2. Like Linux commands, the names of the bash variables are case-sensitive. Typically we define environment variables in UPPER CASE names only and are considered best practice, but this is not required.
  3. By default, the Linux variable scope is LOCAL. We can make them GLOBAL (or environmental variable) using the export command.

Let us print values of our VAR_NUM, VAR_NUM, MY_OS, and other variables defined earlier using various commands:

echo "$VAR_NUM"
echo "$MY_OS"
printf "%s\n" "$DOMAIN_NAME"
echo $is_backup_failed

Unsettling / removing shell variable and values

We can unset values and attributes of shell variables and functions using the unset command:

unset var_name
unset MY_OS
unset is_backup_failed

How to set read-only environment variables in Linux when using bash

We use the readonly command as follows:

readonly var=value
readonly PI=3.14
export PI # Make it enviorment/global var 
echo "$PI"
bash -c "echo $PI"
unset PI
Bash set up read only varible Linux command

Setting up unchangeable read-only bash variable on my Ubuntu Linux desktop

Accessing user-defined variables in sub-shells and other instances

Let us start a new instance of bash, enter and try to print values as follows:

# 1. Define mysql_bak_dest and _mysql_dump variables 
# 2. Print 'mysql_bak_dest' and '_mysql_dump' variables
echo "$mysql_bak_dest" 
echo "$_mysql_dump"
# 3. start a new shell 
# 4. Can you print 'mysql_bak_dest' and '_mysql_dump' variables ?
echo "$mysql_bak_dest" 
echo "$_mysql_dump"
# 5. Exit and go back parent shell session and print 'mysql_bak_dest' and '_mysql_dump' variables
echo "$mysql_bak_dest" 
echo "$_mysql_dump"
# 6. Can you use the printenv to print 'mysql_bak_dest', '_mysql_dump', 'HOME' variable ?
printenv mysql_bak_dest
printenv $_mysql_dump
printenv HOME
How to Set and List Environment Variables in Linux

Setting and listing environment LOCAL variables on Linux

In step # 4, the output is empty. But why? It means the variables we defined are not environment variables, and they are LOCAL. In a sub-shell and other new shell instances, variables values are not exported. Hence, we use the export command to make them GLOBAL or environment variables. For instance:

export var=value
# make them GLOBAL or environment variable 
export mysql_bak_dest="/aws/efs"
export _mysql_dump="/usr/bin/mysqldump"
echo "$mysql_bak_dest" 
echo "$_mysql_dump"
# Start a new sub-shell or instance by tping the 'bash' and try to access GLOBAL or environment vars 
bash -c "echo $mysql_bak_dest; echo $_mysql_dump"
How to Set Environment Variables in Linux

Setting environment (GLOBAL) variables in Linux using export for the current and exported user bash session

export command

You can modify each environmental or system variable using the export command. Set the PATH environment variable to include the directory where you installed the bin directory with perl and shell scripts:

export PATH=${PATH}:/home/vivek/bin


export PATH=${PATH}:${HOME}/bin

To set the JAVA_HOME environment variable to the directory where you installed the J2SE SDK application, enter:

export PATH=${PATH}:/usr/java/jdk1.5.0_07/bin

You can set multiple paths as follows:

export ANT_HOME=/path/to/ant/dir
export PATH=${PATH}:${ANT_HOME}/bin:${JAVA_HOME}/bin

A note about env and setting up variables

First set NFS_ROOT variable to /efs/ec2/wwwdata and run perl script called
env NFS_ROOT=/efs/ec2/wwwdata
In this example, run ‘vim’ with the environment containing ‘LOGNAME=nixcraft’,and ‘DISPLAY=desktop2:0’:
env - DISPLAY=desktop2:0 LOGNAME=nixcraft vim /path/to/file
Set FOO to bar and print it with perl:
env - FOO=bar /usr/bin/perl -e 'print "$FOO \n"'
We can’t see $FOO from shell as it was only defined for perl code:
echo "$FOO"

How Do I Make All Environment Variables Settings Permanent/Persistent on Linux?

The ~/.bash_profile ($HOME/.bash_profile) or ~/.profile file is executed when you login using console or remotely using ssh. Type the following command to edit ~/.bash_profile file, enter:
$ vi ~/.bash_profile
Append the $PATH settings, enter:
export PATH=${PATH}:${HOME}/bin
Save and close the file.

Set IBM DB2 Instance Name

Type the following command:

export DB2INSTANCE=prod_sales

A Note About /etc/profile File

/etc/profile or /etc/profile.d/ directory contains Linux system wide environment and startup programs. It is used by all users with bash, ksh, sh shell. Usually used to set PATH variable, user limits, and other settings for user. It only runs for login shell. If you wanted to make large changes or application specific changes use /etc/profile.d/ directory as explained here and here.
See the following resources:

File Purpose Examples (use the cat to view a file)
/etc/environment Set up system-wide environment variables.
/etc/profile Linux system-wide .profile file for the Bourne shell (sh) and Bourne compatible shells such as bash, ksh, ash, and others.
if [ "${PS1-}" ]; then
  if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
      PS1='$ '
if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
  unset i
/etc/profile.d/ All large user and site specific environment customization should be placed in this directory. This is also system-wide. $ ls -l /etc/profile.d/
$ cat /etc/profile.d/gawk.csh

gawkpath_default () {
	unset AWKPATH
	export AWKPATH=`gawk 'BEGIN {print ENVIRON["AWKPATH"]}'`
gawkpath_prepend () {
	[ -z "$AWKPATH" ] && AWKPATH=`gawk 'BEGIN {print ENVIRON["AWKPATH"]}'`
	export AWKPATH="$*:$AWKPATH"
gawkpath_append () {
	[ -z "$AWKPATH" ] && AWKPATH=`gawk 'BEGIN {print ENVIRON["AWKPATH"]}'`
	export AWKPATH="$AWKPATH:$*"
gawklibpath_default () {
gawklibpath_prepend () {
	[ -z "$AWKLIBPATH" ] && \
gawklibpath_append () {
	[ -z "$AWKLIBPATH" ] && \
$HOME/.bash_profile The personal initialization file, executed for login shells.
/usr/bin/keychain /root/.ssh/id_ed25519
source /root/.keychain/$HOSTNAME-sh
$HOME~/.bashrc The individual per-interactive-shell startup file.
PS1='${debian_chroot:+($debian_chroot)}\h:\w\$ '
umask 022
export LS_OPTIONS='--color=auto'
export PATH="$HOME:/home/vivek/bin"
eval "`dircolors`"
alias ls='ls $LS_OPTIONS'
alias ll='ls $LS_OPTIONS -l'
alias l='ls $LS_OPTIONS -lA'
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
$HOME/.bash_logout The individual login shell cleanup file, executed when a login shell exits
if [ "$SHLVL" = 1 ]; then
    [ -x /usr/bin/clear_console ] && /usr/bin/clear_console -q

Summing up

You learned how to set and list environment variables on Linux when using bash:

Command Description Example(s)
declare command Declare bash variables and give them attributes such as integer, indexed arrays, associative arrays, readonly and so on If no variables or options are given to declare, it will display the attributes and values of all (variables same as running set) See ‘help declare’

declare | grep BASH
declare | grep function_name
# Make sure str_size have the 'integer' attribute 
declare -i db_size=20
echo $db_size # will print 20
echo $db_size # will print 0 
# Set max size for linux container and make it read-only too 
declare -ir MAX_MEM_FOR_CONTAINER=4096
env command Run a program in a modified environment. Print all environment variables.
env | more
env | grep SERVER_ROOT
export command Command that sets environment (GLOBAL) variables and export environment to a sub-shell or other instances. export NFS_ROOT=/aws/ec2/efs
printenv command Print all or part (given) of environment variables on Linux.
printenv SHELL
printenv | egrep 'SHELL|PS1|PS2'
readonly command Mark shell variables as unchangeable i.e. read-only or constant shell variable
readonly K_VERSION="1.9.52"
set command Set or unset values of shell options and positional parameters. Also, displayes all environment variables. See ‘help set’

set | more
set -- $MY_DOMAINS
echo "$1"
echo "$2"
echo "$3"
for d in $@
  echo "Working on $d ..."
unset command Removes shell and environment variables. Not all variables can be unset. For example, read-only variables can not be unset. unset FOO

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 23 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
23 comments… add one
  • ./ Apr 15, 2011 @ 9:55

    Setting en variable
    1) If u want to set the environment variables which will be global to all the users on the Linux box:
    then u can modify the /etc/profile file
    To bring the change u made to it in effect: do either of these –
    a) source /etc/profile
    b) su – root
    c) Relogin to the machine

    2) If you want the environment variables to be set only for your user:
    then modify the ~/.bash_profile file and set the env. variables there.

    To bring the change u made to it in effect: do either of these –
    a) source ~/.bash_profile
    b) su – username
    c) Relogin to the machine

    • Colin Richardson Oct 13, 2016 @ 7:26

      Thank you, I forgot about the source part to kick them into working immediately.

  • ne0 Apr 19, 2011 @ 12:30

    In Ubuntu, the bash_profile called bashrc:
    $ vim ~/.bashrc

  • Pawankumar Jajara Aug 16, 2011 @ 19:34

    Nice Website !!

    I always find decent solutions for Linux commands/script problems and they are handy and ready to copy paste. I would recommend anyone using the content on this website to directly execute on their machines.


  • Noor Kaloon Nov 26, 2011 @ 1:06

    useful blog..lots of good info

    I need to set 2 different java versions in my Linux one app requires jdk1.4.2_19 & another app. needs jdk1.5.0_06 (both must run at the same time on the same Linux machine Amazon AMI machine)

    Any pointers on how to do this?

    Thanks in advance

    • Anonymous Feb 4, 2014 @ 20:20

      I assume you have both vms installed. I would create a launcher script for each program, using an absolute file path to the appropriate java executable.

      Alternatively, I suppose you could leave java out of your path statement and create a launch script that appends the correct java’s bin directory to the path with the export command discussed above before launching.

      Note that I have not tested either option but I see no reason why they wouldn’t work.

  • SaliproIT Mar 27, 2012 @ 15:21

    thanks so much! It help me solving many problem.

  • Juan Aug 2, 2012 @ 18:04

    Thanks for the post.

    There’s a typo though, where it says:
    vi ~/.bash_proflle

    it should be:
    vi ~/.bash_profile

    • lion Mar 20, 2013 @ 3:47


    • Uyen Dec 26, 2016 @ 9:51

      Great. It works.

  • raghavendra K Sep 19, 2012 @ 19:10

    thanks ! it helped me to know some things about linux.

  • Pradeep Kumar Sep 20, 2012 @ 13:47

    Hello Vivek,

    For a beginner on linux like me, it is very helpful. Thanks for the post.


  • lalio Oct 2, 2012 @ 0:12

    Hello, I was confused a bit for the command export: in some site and document, sometime the commands for setting the path are:
    export PATH=$PATH:/blabla
    export PATH=”$PATH”:/blabla
    and export PATH=${PATH}:/blabla (as you wrote above)
    So I wonder which one is the correct command and if they are right in some situation, which one should I use for which case? Please specify them for me. I’m learning more about Linux. Thank you in advance

  • Hitesh Prajapti Dec 20, 2012 @ 12:50

    Thanks, Providing good information.

  • raju sahani Mar 13, 2013 @ 8:07

    thanks 2 providing good knowledge

  • lion Mar 20, 2013 @ 3:42

    hi ./

    maybe “init q” is useful; ah…must redhat os;

  • laike9m Sep 8, 2013 @ 1:35

    This really helps!

  • Steven Feb 6, 2014 @ 23:57

    convert was exiting with the message “Killed” or just outright segfaulting on me.

    I set CONVERT_ARGS to “-limit memory 1 -limit map 1” as suggested here:

    That solved the problem. It probably slowed things down a bit, but that wasn’t a big deal for me.

  • Steven Feb 7, 2014 @ 0:00

    I posted this to the wrong tab.. oops.

  • Santak Dalai May 10, 2014 @ 14:25


    I am facing a situation where I have to link a library at run time. I don’t have LD_RUN_PATH defined in my system. When I try to set this variable using: setenv $LD_RUN_PATH=usr/lib . But I get this error message: LD_RUN_PATH: Undefined variable.
    Is there a way to create an environment variable in linux?

  • Mahendra Thapa Jun 27, 2014 @ 2:23

    Very good documentation !!! I am able to fix my problem(s) just following steps.

  • Riya Sep 16, 2020 @ 6:50

    Great post, it helped me to learn new things about Linux. Thank you for sharing.

  • anisbet Jan 19, 2021 @ 19:23

    Hi, very helpful article. One spelling mistake; in the summing up section you wrote ‘


    ‘ as ‘



    Great reference!

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum