Sunday, 18 December 2016

Bash Scripting Variables - Environment and Special Shell Variables

Variables in Shell Scripting - In the last article, we introduced to Shell Scripting. Now, moving further, we will study very basic component of shell scripts, or rather any computer program - Variables. Those who have been programming or learned to program, will be quite used to this term. This article is for those, who do not have any programming background and are new to programming world. Other can read this article for a refresher.


A variable is a named location in memory that stores a value. In simpler words, when we create a variable and assign a value to it, the operating system reserves a memory location and stores the value in it. This memory location can then be identified or accessed with a variable name. Thus, with a variable, we can store a value in to the memory and read it as and when needed.

Variables Basics

In Bash, a variable may store a character string, a number or even the output of a command. A variable myVar can be set a string value 'myValue' or a number 777 or the output of the command ls myFile using the assignment operator =. Please note some points about variables as below:

  1. A variable name may consist of uppercase or lowercase letters or even mixture of them.
  2. A variable name may contain a number, but it should start with a alphabetical character.
  3. Variables are case-sensitive, meaning that myVar, MYVAR and myvar are three different variables and point to dissimilar memory locations.
  4. A value can be assigned to a variable name using the assignment operator =.
  5. A value can be retrieved from a variable, by using $ sign before a variable name, e.g. $myVar.
  6. Values enclosed within " " or ' ', is treated as single value. When a value contains spaces, it should be included within single or double quotes.
  7. Single quotes store the value literally, while values within double quotes can be substituted.
Lets check this on terminal.

# Point #1, #2, #3, #4 - Setting and using variable names
[root@LinuxBox ~]$ myName=Mandar
[root@LinuxBox ~]$ MYNAME=MANDAR
[root@LinuxBox ~]$ myname=mandar

# Point #5 - Retrieving a value
[root@LinuxBox ~]$ echo $myName
Mandar
[root@LinuxBox ~]$ echo $MYNAME
MANDAR
[root@LinuxBox ~]$ echo $myname
mandar

# Point 6 - Importance of quotes
 # Without quotes - 'Shinde' is considered as shell command
[root@LinuxBox ~]$ myName=Mandar Shinde
-bash: Shinde: command not found

 # With quotes - everything inside is considered as a value
[root@LinuxBox ~]$ myName='Mandar Shinde'
[root@LinuxBox ~]$ echo $myName
Mandar Shinde

# Point 7 - Single quotes store value literally, Double quotes substitute them
[root@LinuxBox ~]$ myName='Mandar Shinde'
[root@LinuxBox ~]$ echo 'My name is $myName'
My name is $myName        # Stores $myName literally
[root@LinuxBox ~]$ echo "My name is $myName"
My name is Mandar Shinde  # Substitutes the value stored in 'myName'

Environment Variables

Each process is associated with an environment - a collection of variables which can be used by the process, known as Environment Variables. Any terminal session, being a process, also its own environment variables. In our previous article, we used one of the Environment variables - $PATH. Their values are set by the shell. You can see the list of all environment variables using printenv command on the terminal.

[root@LinuxBox ~]$ printenv
HOSTNAME=LinuxBox
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
SSH_TTY=/dev/pts/0
USER=root
MAIL=/var/spool/mail/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
PWD=/root
LANG=en_US.UTF-8
HISTCONTROL=ignoredups
SHLVL=1
HOME=/root

We can use these variables, without any need to declare them, as shell has already done this for us. One can also change them if needed, as we normally do with $PATH, while adding a directory in the search path. Let's check this.

# Before adding '/root' to path
[root@LinuxBox ~]$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

# Adding '/root' to path -> PATH = $PATH + ':/root'
[root@LinuxBox ~]$ PATH="$PATH:/root"

# After adding '/root' to path
[root@LinuxBox ~]$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root

We can use these variables in our scripts or even on terminal as follows:

[root@LinuxBox ~]$ echo "Hello $USER. This shell is $SHELL and your home directory is $HOME."
Hello root. This shell is /bin/bash and your home directory is /root.

Note : When we declare a variable on the terminal, its value is valid only for that session. If you start another session, all the values stored are gone. If one wants a variable value to be available as soon as session loads, he can edit the /etc/profile or ~/.bash_profile or ~/.bashrc file and set the variable with the desired value.

Special Shell Variables

There is another collection of variables accessible to the users, created by the shell and can be used in shell scripts. Below is the list of these variables. Just have a look at them, don't panic if it seems hard to learn, it will look easy when we see them in the example.

  • $0 - File name of the script which is running
  • $1 - First argument to the script
  • $2 - Second argument to the script
  • $N - Nth argument to the script
  • $# - Total number of arguments provided to the script
  • $* - All the arguments as a single value within double quotes, "$1 $2 ..."
  • $@ - All the arguments with each argument individually double quoted, "$1" "$2" ...
  • $$ - Process ID of the current process, a script or current terminal session.
  • $? - Exit status of last executed command. Exit status '0' denotes successful execution or otherwise.
To study all these variables, we write a script as below, and provide four arguments to it while executing it.

#!/bin/bash

echo "File name of current running script : $0"
echo "First argument to the script : $1"
echo "Second argument to the script : $2"
echo "Third argument to the script : $3"
echo "Total number of arguments : $#"
echo "All arguments to the script : $@"
echo "All arguments to the script : $*"
echo "PID of this process : $$"

Output:

File name of current running script : myScript.sh
First argument to the script : arg1
Second argument to the script : arg2
Third argument to the script : arg3
Total number of arguments : 4
All arguments to the script : arg1 arg2 arg3 arg4
All arguments to the script : arg1 arg2 arg3 arg4
PID of this process : 2797

To demonstrate the use of $? shell variable, we use ls command as below. It returns '0' if the command executes successfully, or returns a non-zero exit status, indicating that there was some error while executing the last command.

# Successful execution -> Exit status = 0
[root@LinuxBox ~]$ ll myFile.txt
-rw-r--r--. 1 root root 201 Aug 26 00:32 myFile.txt
[root@LinuxBox ~]$ echo $?
0

# Unsuccessful execution -> Exit status != 0
[root@LinuxBox ~]$ ll myFile.pdf
ls: cannot access myFile.pdf: No such file or directory
[root@LinuxBox ~]$ echo $?
2

This was all about the variables used in Shell scripting. We have learned to create variables and storing value into them. We have also learned about Environment and special shell variables, in this article. Please share your views in the comment section below and stay tuned. Thank you.

0 comments:

Post a Comment