In shell scripting, variables are used to store data, such as strings, numbers, and special values. Unlike other programming languages, shell scripting does not require explicit data type declarations. Everything is treated as a string by default.
Table of Contents
Toggle1. Declaring and Using Variables
Syntax:
variable_name=value
-
No spaces before or after
=
-
Variables are case-sensitive (
myVar
andMYVAR
are different)
Examples:
name="John"
age=25
echo "My name is $name and I am $age years old."
πΉ Use $variable_name
to access the value of a variable.
Reading User Input:
echo "Enter your name:"
read user_name
echo "Hello, $user_name!"
2. Variable Types
a) Local Variables
These variables are defined in a script or terminal session and are not accessible outside it.
my_var="Hello"
echo $my_var
b) Environment Variables
System-wide variables available to all processes. Examples: $HOME
, $PATH
, $USER
echo "Home directory: $HOME"
echo "Current user: $USER"
To define an environment variable:
export MY_ENV_VAR="This is an environment variable"
c) Special Variables
Shell provides built-in special variables:
Variable | Description |
---|---|
$0 |
Script name |
$1, $2, β¦ |
Positional parameters (arguments passed to the script) |
$# |
Number of arguments passed |
$@ |
All arguments as separate words |
$* |
All arguments as a single string |
$? |
Exit status of the last command (0 = success, non-zero = error) |
$$ |
Process ID (PID) of the current script |
$! |
PID of the last background process |
Example:
echo "Script Name: $0"
echo "First Argument: $1"
echo "Number of Arguments: $#"
3. Constants (Read-Only Variables)
Use readonly
or declare -r
to prevent modification.
readonly PI=3.14
declare -r MAX_USERS=100
4. Command Substitution in Variables
You can store the output of a command in a variable:
current_date=$(date)
echo "Today's date is: $current_date"
Or using backticks `command`
:
current_user=`whoami`
echo "Logged in as: $current_user"
5. Data Types (Emulated)
Since Bash treats everything as a string, data types must be handled explicitly.
a) String Variables
greeting="Hello, World!"
echo $greeting
String operations:
length=${#greeting} # Get length
echo "String Length: $length"
b) Integer Variables
To perform arithmetic, use (( ))
or expr
:
num1=10
num2=5
sum=$((num1 + num2))
echo "Sum: $sum"
Or using expr
:
sum=`expr $num1 + $num2`
echo "Sum: $sum"
c) Boolean Variables
Bash does not have built-in boolean types, but 0
is used for βtrueβ and non-zero for βfalse.β
isValid=1 # 1 for true, 0 for false
if [ $isValid -eq 1 ]; then
echo "Valid"
else
echo "Not Valid"
fi
6. Unset and Default Values
-
Unset a variable:
bashunset my_var
echo $my_var # Outputs nothing
-
Set a default value if the variable is empty:
bashecho ${var_name:-"Default Value"}
π Summary
β
Variables do not require type declaration.
β
Everything is treated as a string unless explicitly handled as a number.
β
Environment variables persist across sessions.
β
Special variables help manage script execution.
β
Use $(( ))
or expr
for arithmetic operations.
Hereβs a hands-on example script that demonstrates different types of variables and operations in shell scripting.
π Shell Script: Working with Variables
Save this script as variables_demo.sh
and run it using bash variables_demo.sh
.
#!/bin/bash
# Defining variables
name="Alice"
age=30
pi=3.14159
# Displaying variable values
echo "Hello, my name is $name and I am $age years old."
echo "Value of Pi: $pi"
# Reading user input
echo -n "Enter your city: "
read city
echo "You live in $city."
# Arithmetic operations
num1=10
num2=5
sum=$((num1 + num2))
diff=$((num1 - num2))
prod=$((num1 * num2))
quot=$((num1 / num2))
echo "Arithmetic Operations:"
echo "$num1 + $num2 = $sum"
echo "$num1 - $num2 = $diff"
echo "$num1 * $num2 = $prod"
echo "$num1 / $num2 = $quot"
# Using special variables
echo "Script Name: $0"
echo "First Argument: $1"
echo "Total Arguments: $#"
# Using a command inside a variable
current_date=$(date)
echo "Current Date: $current_date"
# Read-only variable
readonly constant_var="I am constant"
echo $constant_var
# constant_var="New value" # This will cause an error
# Unsetting a variable
unset name
echo "Name after unset: $name" # Output will be empty
# Setting default value if variable is empty
echo "User: ${username:-'Guest'}"
πΉ How to Run the Script
-
Save the file as
variables_demo.sh
-
Give it execution permission:
bashchmod +x variables_demo.sh
-
Run the script:
bash./variables_demo.sh
πΉ Features Demonstrated in This Script
β
Variable declaration and usage
β
Reading user input
β
Arithmetic operations
β
Special variables like $0
, $1
, $#
β
Using command substitution $(command)
β
Read-only variables (readonly
)
β
Unsetting and default values (unset
, ${var:-"default"}
)