The variables are building blocks of all programming languages as it allows us to store data in them and use it later on. In a shell script, creating and using variables is different from other programming languages, such as Python, Java, and so on.
In shell scripting, a variable name can contain the following:
We cannot use any other special characters (%
, $
, -
) because they hold a particular purpose in shell scripting. Some valid examples of the variable names are given below.
VAR
VAR1
VAR_1
NEW_VARIABLE
Note: Traditionally, variable names in shell scripting are in UPPERCASE.
The variables are defined and assigned a value using the =
operator. Here's the syntax.
VARIABLE_NAME=VARIABLE_VALUE
Let's look at an example where we define the variable MY_NAME
and assign a value to it.
MY_NAME="Kedar"
Note: There should not be any space before and after the
=
operator. The terminal is attached to the end of the shot. Please copy the commands from above and paste them into the terminal to try them.
To use the value stored in the variable, we prefix it with the $
sign. Let's use the value from the variable MY_NAME
, which we defined above.
root@educative:/# MY_NAME="Kedar"root@educative:/# echo "My name is $MY_NAME"My name is Kedar
MY_NAME
and assign a value Kedar
to it.My name is kedar
using the variable MY_NAME
.