User-Defined Variables in Shell Scripting

Variables in shell scripting are an essential part of managing dynamic values within your scripts. They act as pointers to data, enabling you to manipulate and utilize values efficiently.

What is a Variable?

  • A variable is a character string that represents a value.
  • It is a pointer to the actual data stored in memory.
  • Shell allows you to create, assign, and delete variables dynamically.

Rules for Variable Names

  1. Variable names can include:
    • Letters (a-z, A-Z),
    • Numbers (0-9), and
    • Underscores (_).
  2. Invalid Characters:
    • No spaces or special characters (e.g., -, !, *).
  3. Variable names cannot begin with a number.
  4. Variable names cannot be reserved shell keywords.
  5. By convention, variable names are often written in UPPERCASE.

Examples of Valid Variable Names:

_VARIABLE_NAME
VARIABLE_NAME
VARIABLE_1_NAME

Examples of Invalid Variable Names:

2_VARNAME    # Starts with a number
-VARIABLE    # Contains a hyphen
VARIABLE!    # Contains an exclamation mark

Defining and Using Variables

Syntax:

variable_name=value

Note: No spaces around the = sign.

Example:

MY_MESSAGE="Hello World"

Examples and Output

Example Script:

#!/bin/bash
# variable_example.sh
name="Saurav"
age="20"
work="programm"
var="ing"

# Printing values
echo "Name: ${name}"
echo "Age: ${age}"
echo "I am ${work}${var}."

# Incorrect variable reference
echo "I am $working"  # 'working' not defined

Output:

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./variable_example.sh
Name: Saurav
Age: 20
I am programming.
I am

Common Errors

  1. Missing quotes or incorrect use of spaces:
    MY VARIABLE=Hello World  # Incorrect (spaces not allowed)
    MY_VARIABLE="Hello World"  # Correct
    
  2. Using undefined variables:
    echo $undefined_var  # Prints nothing
    

Advanced Examples

Variable Scope:

#!/bin/bash
# variable_scope.sh

# Variables with different cases
name="Gaurav"
NAME="Saurav"
nAmE="Amit"

echo "Different Variables: ${name}, ${NAME}, ${nAmE}"

# Using underscores in variable names
_variableName="First variable"
echo "${_variableName}"

Output:

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./variable_scope.sh
Different Variables: Gaurav, Saurav, Amit
First variable

Invalid Variable Names:

#!/bin/bash
# invalid_variable.sh

3variable="Invalid"
variable-name="Invalid"

Output:

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./invalid_variable.sh
./invalid_variable.sh: line 2: 3variable=Invalid: not found
./invalid_variable.sh: line 3: variable-name=Invalid: not found

Best Practices

  • Always use meaningful variable names.
  • Use UPPERCASE for constant values.
  • Ensure proper quoting to avoid unexpected behavior.
  • Follow naming conventions to improve readability and maintainability.

Demo Video

Click Here for Demo Video

Stay tuned for the next tutorial, where we’ll explore system-defined variables in shell scripting. Happy scripting!