Operations on Variables
We can perform both numerical and string operations on variables on Bash scripting. An example of the same is given below –
Example Script:
NUM1=10 #variable 1
NUM2=5 #variable 2
# Numerical Operations over the variables
SUM=$(( $NUM1 + $NUM2 ))
SUBTRACT=$(( $NUM1 - $NUM2 ))
MULTIPLY=$(( $NUM1 * $NUM2 ))
DIVIDE=$(( $NUM1 / $NUM2 ))
echo "Addition : $SUM"
echo "Subtraction : $SUBTRACT"
echo "Multiply : $MULTIPLY"
echo "Divide : $DIVIDE"
# String Operations over the variables
NAME="w3wiki"
echo ${NAME:0:5} #substring extraction
FIRST_NAME="Isaac"
LAST_NAME="Newton"
echo ${FIRST_NAME}" "${LAST_NAME}
Output of Operations on Variables:
Addition : 15
Subtraction : 5
Multiply : 50
Divide : 2
Geeks
Isaac Newton
In the above example, we have performed different numerical operations like addition, subtraction, multiplication, and division using variables and also performed basic string operations like concatenation and substring extraction. Below is the terminal shell depiction after executing the script –
Bash Script – Working of Bash Variables
A Bash script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a reusability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can use that file for executing the set of commands one or more times as per our requirements. In programming, a variable is a value that can change, depending on conditions or on information passed to the program. A variable in bash can contain a number, a character, or a string of characters. Here in this article, we are going to discuss the working of variables within Bash Scripting.
Rules for defining variables in Bash Scripts are as follows –
- Variable names can contain uppercase, lowercase letters, numbers, underscores, and digits.
- It is a good practice to use uppercase letters for variable names within Bash scripts.
- Space is not allowed.
- Pre-defined keywords cannot be used. Like if, else, etc.
The simplest example of the use of variables in Bash scripting can be given as –
Example Script:
NAME="Satyajit Ghosh"
echo "His name is $NAME"
Output:
His name is Satyajit Ghosh
The above example shows a variable ‘name‘. Then it is used with an echo command to display its value. So, the basic syntax for writing variables within a Bash Script will be –
Syntax of Writing Variables:
VariableName=value
echo $VariableName #for accessing the value
If we want to change the value of a variable then we can do that. The basic syntax for that will be –
VariableName=value
VariableName=newValue
echo $VariableName #for accessing the value
Below is an example of the same –
Example Script:
AGE=10 #assigning a value
AGE=20 #changing the value
echo $AGE #display the value
Output:
20
Below is the terminal shell depiction after executing the script –