Assign values to shell variables (PATH variable)

Creating and setting variables within a script is fairly simple. Use the following syntax:

varName=someValue

someValue is assigned to given varName and someValue must be on right side of = (equal) sign. If someValue is not given, the variable is assigned the null string.

How Do I Display The Variable Value?

You can display the value of a variable with echo $varName or echo ${varName}:

echo "$varName"

OR

echo "${varName}"

OR

printf "${varName}"

OR

printf "%s\n" ${varName}

For example, create a variable called vech, and give it a value ‘Bus’, type the following at a shell prompt:

vech=Bus

Display the value of a variable vech with echo command:

echo "$vech"

OR

echo "${vech}"

Create a variable called _jail and give it a value “/httpd.java.jail_2”, type the following at a shell prompt:

_jail="/httpd.java.jail_2"
printf "The java jail is located at %s\nStarting chroot()...\n" $_jail

However,

n=10 # this is ok
10=no# Error, NOT Ok, Value must be on right side of = sign.

Common Examples

Define your home directory:

myhome="/home/v/vivek"
echo "$myhome"

Set file path:

input="/home/sales/data.txt"
echo "Input file $input"

Store current date (you can store the output of date by running the shell command):

NOW=$(date)
echo $NOW

Set NAS device backup path:

BACKUP="/nas05"
echo "Backing up files to $BACKUP/$USERNAME"

Setting Environment Variables in Linux (Using Bash Shell) : How-To

What are Environment Variables?

Environment variables are what define the shell. They help the shell to find the location of various programs so that they can be run, the location of the home folder so that the shell can understand when when we mention something like ~/ and other customizations that we take for granted that the terminal will do. There are two kinds of environmental variables – Global Variables and Local Variables

  • Global Variables: These variables provide the settings for all terminals spawned by a particular terminal. These are set automatically when the bash session gets started
  • Local Variables: These variables provide the settings only for the terminal through which they are set. These are usually set by processes when they are running.

How to view/add/edit/remove Global Variables?

The printenv command is used to view, the export commandis used to add/edit and the unsetcommand is used to remove global variables.

Viewing:

nits@nits-workstation:~$ printenv
ORBIT_SOCKETDIR=/tmp/orbit-nits
TERM=xterm
SHELL=/bin/bash
WINDOWID=71314636
GTK_MODULES=canberra-gtk-module
USER=nits
USERNAME=nits
DEFAULTS_PATH=/usr/share/gconf/gnome.default.path
XDG_CONFIG_DIRS=/etc/xdg/xdg-gnome:/etc/xdg
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
DESKTOP_SESSION=gnome
PWD=/home/nits
GDM_KEYBOARD_LAYOUT=us
GNOME_KEYRING_PID=1638
LANG=en_US.UTF-8
GDM_LANG=en_US.utf8
MANDATORY_PATH=/usr/share/gconf/gnome.mandatory.path
UBUNTU_MENUPROXY=libappmenu.so
COMPIZ_CONFIG_PROFILE=ubuntu
GDMSESSION=gnome
SHLVL=1
HOME=/home/nits
LANGUAGE=en_US:en
GNOME_DESKTOP_SESSION_ID=this-is-deprecated
LOGNAME=nits
_PX_CONFIG_ORDER=
XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-o5GXSSs4jg,guid=fa5c8a536145534d2b6036b900000025
LESSOPEN=| /usr/bin/lesspipe %s
WINDOWPATH=7
DISPLAY=:0
LESSCLOSE=/usr/bin/lesspipe %s %s
IBUS_NO_SNOOPER_APPS=synapse
COLORTERM=gnome-terminal

NOTE: The names of system environment variables that are set by the system itself are always in capital letters so as to help us differentiate between system-set and user-set environmental variables.

Adding:

nits@nits-workstation:~$ adding_test='Adding a test string as a global variable'
nits@nits-workstation:~$ export adding_test
nits@nits-workstation:~$ bash
nits@nits-workstation:~$ echo $adding_test
Adding a test string as a global variable
nits@nits-workstation:~$ exit
exit

Here we created a new string called adding_testand exported it to become a global variable. Then we started a fresh bash shell which is a child process of the terminal that we set the global variable in and when we print the value of the variable adding_text, it printed the value of the variable even in a fresh child process.

Editing:

nits@nits-workstation:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
nits@nits-workstation:~$ export PATH=$PATH:/home/nits/Scripts/
nits@nits-workstation:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/nits/Scripts/
nits@nits-workstation:~$ bash
nits@nits-workstation:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/nits/Scripts/
nits@nits-workstation:~$ exit
exit

Here we saw the contents of the PATH variable (which is one of the global variables) and we appended the location of the directory where our scripts are stored which is/home/nits/Scripts/ and exported it. We checked the value of the PATH variable in the parent terminal and also in the child terminal.

Removing:

nits@nits-workstation:~$ adding_test='Adding a test string as a global variable'
nits@nits-workstation:~$ export adding_test
nits@nits-workstation:~$ echo $adding_test
Adding a test string as a global variable
nits@nits-workstation:~$ unset adding_test
nits@nits-workstation:~$ echo $adding_test

nits@nits-workstation:~$

Here, we exported the adding_test variable and we checked the variable. Upon using the unsetcommand, the variable has gotten removed.

How to view/add/remove Local Variables?

There is no one command to print all the local variables. The set command however, prints all the environment variables present, both global and local variables. Unlike with global variables there is no export command for local variables.

Viewing:

BASH=/bin/bash
BASHOPTS=checkwinsize:cmdhist:expand_aliases:extglob:extquote:force_fignore:histappend:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
BASH_COMPLETION=/etc/bash_completion
BASH_COMPLETION_COMPAT_DIR=/etc/bash_completion.d
BASH_COMPLETION_DIR=/etc/bash_completion.d
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="4" [1]="2" [2]="8" [3]="1" [4]="release" [5]="i686-pc-linux-gnu")
BASH_VERSION='4.2.8(1)-release'
COLORTERM=gnome-terminal
COLUMNS=80
COMPIZ_CONFIG_PROFILE=ubuntu
COMP_WORDBREAKS=$' \t\n"\'><=;|&(:'
DEFAULTS_PATH=/usr/share/gconf/gnome.default.path
DESKTOP_SESSION=gnome
DIRSTACK=()
DISPLAY=:0
GDMSESSION=gnome
GDM_KEYBOARD_LAYOUT=us
GDM_LANG=en_US.utf8
GNOME_DESKTOP_SESSION_ID=this-is-deprecated
GNOME_KEYRING_PID=1638
GROUPS=()
GTK_MODULES=canberra-gtk-module
HISTCONTROL=ignoredups:ignorespace
HISTFILE=/home/nits/.bash_history
HISTFILESIZE=2000
HISTSIZE=1000
HOME=/home/nits
HOSTNAME=nits-workstation

Although not the complete output of set command, you can see many variations between the output of set and printenv commands, that is the addition of extra local variables.

Adding:

nits@nits-workstation:~$ local_add='This is a local variable'
nits@nits-workstation:~$ bash
nits@nits-workstation:~$ echo $local_add

nits@nits-workstation:~$ exit
exit
nits@nits-workstation:~$ echo $local_add
This is a local variable

Assigning value to a variable in a shell makes it a local variable. Here, we created a string variable called local_add. When we spawned a new shell and tried to print the value of local_add variable there, we failed because it is a local variable. But when we got back to our parent terminal and tried printing its value, it did.

Editing:

nits@nits-workstation:~$ echo $local_add
This is a local variable
nits@nits-workstation:~$ local_add=$local_add.'From on here is the text'
nits@nits-workstation:~$ echo $local_add
This is a local variable.From on here is the text

The variable local_add already has a string. We appended another string to the existing value of the local_add variable and then printed the value of the local variable to confirm it.

Removing:

nits@nits-workstation:~$ echo $local_add
This is a local variable.From on here is the text
nits@nits-workstation:~$ unset local_add
nits@nits-workstation:~$ echo $local_add

nits@nits-workstation:~$

Removing a local variable is same as global variable, it is done using the unset command.

Making permanent changes user-wide/system-wide:

User-wide changes:

To make changes for just one particular user, you will have to edit the ~/.bash_profile

nits@nits-workstation:~$ nano ~/.bash_profile

##And inside the file, add/edit your environment variables accordingly -
export PATH=$PATH:/home/nits/Scripts

System-wide changes:

To make changes system-wide , you will have to edit the /etc/environment file. Once you open that file just make the required changes.

nits@nits-workstation:~$ nano /etc/environment/

 ## Make the necessary edits or additions, for example, this is the line in my /etc/environment/ after I edited it to add the Scripts folder in my home directory to it

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/nits/Scripts"

Common errors encountered:

Not a valid identifier error while exporting a variable:

Wrong – Creates Errors

nits@nits-workstation:~$ export $PATH=$PATH:/home/nits/Scripts/
bash: export: `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/nits/Scripts/': not a valid identifier

Correct – No Errors

nits@nits-workstation:~$ export PATH=$PATH:/home/nits/Scripts/

This error is usually encountered when we accidentally type export $PATH instead of exportPATH. There is no $ (dollar-sign) for the variable that is exported.

Linux: Set Environment Variable

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

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. Set environment variables as needed by programs.
  5. Run commands that you want to run whenever you log in or log out.
  6. Setup aliases and/or shell function to automate tasks to save typing and time.
  7. Changing bash prompt.
  8. Setting shell options.

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

Display Current Environment

Type the following command:
$ set
Sample outputs:

BASH=/bin/bash
BASH_ARGC=()
BASH_ARGV=()
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="3" [1]="2" [2]="25" [3]="1" [4]="release" [5]="x86_64-redhat-linux-gnu")
BASH_VERSION='3.2.25(1)-release'
COLORS=/etc/DIR_COLORS.xterm
COLUMNS=237
CVS_RSH=ssh
DIRSTACK=()
EUID=0
GROUPS=()
G_BROKEN_FILENAMES=1
HISTFILE=/root/.bash_history
HISTFILESIZE=1000
HISTSIZE=1000
HOME=/root
HOSTNAME=server3.www.p.cyberciti.biz
HOSTTYPE=x86_64
IFS=$' \t\n'
INPUTRC=/etc/inputrc
LANG=en_US.UTF-8
LESSOPEN='|/usr/bin/lesspipe.sh %s'
LINES=64
LOGNAME=root
LS_COLORS='no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:'
MACHTYPE=x86_64-redhat-linux-gnu
MAIL=/var/spool/mail/root
MAILCHECK=60
OPTERR=1
OPTIND=1
OSTYPE=linux-gnu
PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
PIPESTATUS=([0]="0")
PPID=35469
PROMPT_COMMAND='echo -ne "33]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "07"'
PS1='[\u@\h \W]\$ '
PS2='> '
PS4='+ '
PWD=/root
SHELL=/bin/bash
SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
SHLVL=1
SSH_CLIENT='10.1.3.116 44212 22'
SSH_CONNECTION='10.1.3.116 44212 10.10.29.68 22'
SSH_TTY=/dev/pts/0
TERM=xterm
UID=0
USER=root
_=set
consoletype=pty
tmpid=0
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 printf or echo command:
$ echo "$HOME"
OR
$ printf "%s\n" $HOME
Sample outputs:
/home/vivek

Task: Set Environment Variables on Linux

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

OR

 
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

How Do I Make All Settings permanent?

The ~/.bash_profile ($HOME/.bash_profile) or ~/.prfile file is executed when you login using console or remotely using ssh. Type the following command to edit ~/.bash_profile file, enter:
$ vi ~/.bash_proflle
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 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 changesuse /etc/profile.d/ directory

 
Advertisements

Posted on June 15, 2015, in Linux (Ubuntu/CentOS). Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: