Bash variables are used to store data that scripts can access and manipulate during execution. They can hold different types of values including text, numbers, command output and arrays. Variables make scripts dynamic and reusable by allowing values to change based on input or conditions, rather than being hardcoded. Without them, handling user input, storing intermediate results, or controlling script behavior would be significantly harder to manage.
- No explicit type declaration required (untyped by default)
- Scopes include local, global, environment and special variables
- Values are referenced by prefixing the variable name with a dollar sign ($)
- Enable dynamic behavior through parameter expansion and substitution
Working of Bash variables
In Bash scripting, variables act as placeholders for data that can be accessed and modified during script execution. When a script runs, the shell handles variables in the following way:
- Read the script line by line: Bash interprets each line sequentially.
- Identify defined variables: It detects any variable names and their assigned values.
- Substitute values: Variable names are replaced with their current values wherever they are used.
- Execute commands: Commands are run using the substituted values.
- Repeat the process: Bash continues this process until the end of the script.
- To access a variable’s value, use the $ symbol before its name.
Example
#!/bin/bash
myvar="Gfg"
echo $myvar
- $myvar: Retrieves the value stored in the variable myvar.
- Without $, Bash would treat myvar as a literal string instead of a variable.

Output:

Naming Rules for Bash Variables
Proper naming of variables is essential to avoid errors and ensure clarity in scripts. Bash enforces the following rules for variable names:
- Start with a letter or underscore (_): Variables cannot begin with a number.
- Can include letters, numbers and underscores: No other special characters are allowed.
- Case-sensitive: gfg, Gfg and GFG are considered different variables.
- Avoid special characters: Characters like @, !, *, or spaces are invalid in names.
Examples of Valid Variable Names
#!/bin/bash
#Valid Variable Examples
gfg="Value-1"
GFG="Value-2"
_gfg="Value-3"
g_f_g="Value-4"
March6="Value-5"
echo $gfg
echo $GFG
echo $_gfg
echo $g_f_g
echo $March6

Output:

Examples of Invalid Variable Names
#!/bin/bash