How to create and use variables in a shell script

Overview

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.

Variable names

In shell scripting, a variable name can contain the following:

  1. Letters ( a–z or A–Z )
  2. Numbers ( 0–9 )
  3. Underscores ( _ )

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.

  1. VAR
  2. VAR1
  3. VAR_1
  4. NEW_VARIABLE

Note: Traditionally, variable names in shell scripting are in UPPERCASE.

Defining variables

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.

Accessing variable value

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

Explanation:

  • Line 1: We define a variable MY_NAME and assign a value Kedar to it.
  • Line 2: We are printing the sentence My name is kedar using the variable MY_NAME.
  • Line 3: It shows the output of the command in line 2.
Terminal 1
Terminal
Loading...

Free Resources