Shell Script · Variables

Shell Scripting · Lesson 6

Variables

Understand variables in shell scripting. System and user defined variables. Rules for naming variables. Using variables in real automation scripts.

What Are Variables?

Variables are used to store data that can be reused throughout a script. A variable can hold text, numbers, or command output.

In shell scripting, variables are created dynamically and do not require explicit data types.

Why Use Variables?

Store Data

Store values that can be reused throughout the script.

Avoid Repetition

Change value once and reuse it everywhere.

Dynamic Behavior

Scripts behave dynamically based on variable values.

Types of Variables

  • Local Variables
  • Environment Variables
  • Read-only (Constant) Variables

Variable Examples

1. Defining a Variable

Variables are created by assigning a value without spaces around '='.

terminal — bash
variables
name="Linux"
echo $name

2. Numeric Variable Example

Variables can store numbers and be used in calculations.

terminal — bash
variables
num=10
echo $num

3. Overwriting a Variable

Variables can be reassigned with new values.

terminal — bash
variables
course="Shell"
echo $course
 
course="Linux"
echo $course

4. Read-only (Constant) Variable

Use readonly to make a variable constant.

terminal — bash
variables
readonly PI=3.14
echo $PI
 
PI=3.1415 # This will cause an error

5. Environment Variable

Environment variables are available to child processes.

terminal — bash
variables
export CITY="Delhi"
echo $CITY

Best Practices

Good Practices

  • Use meaningful variable names.
  • Avoid spaces around '='.
  • Use uppercase for constants.
  • Quote variables to prevent word splitting.

Practice Task – Variables

  • Create a variable named name and print it.
  • Create a variable age and update its value.
  • Create a constant variable using readonly.
  • Export a variable and verify it using env.

Next lesson: User Input (read command)