Shell Scripting part-2| Variable & scope

Shell Scripting part-2| Variable & scope

Variables are place holders to hold values. Variables are key-value pairs.

In Shell programming, there are no data types. Every value is treated as text type or string type.

All variables are divided into 2 types--

  1. Environment variables / predefined variables

  2. User defined variables

1)Environment Variables:

These are predefined variables and mostly used internally by the system. Hence these variables also known as System variables.

But based on our requirement, we can use these variables in our scripts. We can get all environment variables information by using either env command or set command.

abarik@abhijit-virtualbox:~$ env
SSH_AGENT_PID=13991
XDG_SEAT=seat0
PWD=/home/abarik
XDG_SESSION_DESKTOP=
LOGNAME=abarik
QT_QPA_PLATFORMTHEME=lxqt
XDG_SESSION_TYPE=x11
GPG_AGENT_INFO=/run/user/1000/gnupg/S.gpg-agent:0:1
XAUTHORITY=/home/abarik/.Xauthority
HOME=/home/abarik

2)User defined Variables:

Based on our programming requirement, we can define our own variables also.

abarik@abhijit-virtualbox:~$ GUEST=SACHIN
abarik@abhijit-virtualbox:~$ echo "Hello $GUEST You are my Hero" 
Hello SACHIN You are my Hero

Rules to define Variables:

  1. It is recommended to use only UPPER CASE characters.

  2. If variable contains multiple words, then these words should be separated with _ symbol.

  3. Variable names should not starts with digit. abarik@abhijit-virtualbox:~$ 12A=40 12A=40: command not found

  4. We should not use special symbols like -,@,# etc

How to define Readonly Variables:

We can define read only variables by using readonly keyword.

$A=100 $readonly A $A=300

bash: A: readonly variable

If the variable is readonly then we cannot perform reassignment for that variable. It will become constant.

Variable Scopes: There are 3 scopes available for variables.

  1. Session Scope

  2. User Scope

  3. System Scope

1) Session Scope: The variables which are declared in the terminal are said to be in session scope.

Once we close the terminal (ie exit session) automatically all variables will be gone. $ X=10 $ Y=10

2) User Scope:

The variables which are declared inside .bashrc file, are said to be in user scope.

These variables are available for all sessions related to current user. These variables cannot be accessed by other users.

3) System Scope:

If the variable available for all users and for all sessions, such type of variables are said to be in system scope.

We have to declare these variables inside /etc/profile file. But to edit this file compulsory root permissions must be required.

$ sudo gedit /etc/profile