• Skip to main content
  • Skip to primary sidebar
  • Home
  • WordPress
  • web Hosting
  • linux
  • mysql
  • nginx
  • apache2
  • devops

Raju Ginni

wordpress tutorials seo hosting etc

You are here: Home / Linux sysadmin tutorials linux system administrator / Variables and Data Types in Shell Scripting

Variables and Data Types in Shell Scripting

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

Toggle
  • 1. Declaring and Using Variables
    • Syntax:
    • Examples:
    • Reading User Input:
  • 2. Variable Types
    • a) Local Variables
    • b) Environment Variables
    • c) Special Variables
  • 3. Constants (Read-Only Variables)
  • 4. Command Substitution in Variables
  • 5. Data Types (Emulated)
    • a) String Variables
    • b) Integer Variables
    • c) Boolean Variables
  • 6. Unset and Default Values
    • πŸš€ Summary
    • πŸ“Œ Shell Script: Working with Variables
    • πŸ”Ή How to Run the Script
    • πŸ”Ή Features Demonstrated in This Script

1. Declaring and Using Variables

Syntax:

bash
variable_name=value
  • No spaces before or after =

  • Variables are case-sensitive (myVar and MYVAR are different)

Examples:

bash
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:

bash
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.

bash
my_var="Hello"
echo $my_var

b) Environment Variables

System-wide variables available to all processes. Examples: $HOME, $PATH, $USER

bash
echo "Home directory: $HOME"
echo "Current user: $USER"

To define an environment variable:

bash
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:

bash
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.

bash
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:

bash
current_date=$(date)
echo "Today's date is: $current_date"

Or using backticks `command`:

bash
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

bash
greeting="Hello, World!"
echo $greeting

String operations:

bash
length=${#greeting} # Get length
echo "String Length: $length"

b) Integer Variables

To perform arithmetic, use (( )) or expr:

bash
num1=10
num2=5
sum=$((num1 + num2))
echo "Sum: $sum"

Or using expr:

bash
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.”

bash
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:

    bash
    unset my_var
    echo $my_var # Outputs nothing
  • Set a default value if the variable is empty:

    bash
    echo ${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.

bash
#!/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

  1. Save the file as variables_demo.sh

  2. Give it execution permission:

    bash
    chmod +x variables_demo.sh
  3. 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"})

Primary Sidebar

Linux sysadmin tutorials linux system administrator

  • top 10 apt & apt-get commands (most used) apt vs apt-get
  • If-Else Statements in Shell Scripting
  • linux commands pdf (files & Directories, zip & unzip process, search etc)
  • Find Files with Specific Text on Linux grep find command
  • linux performance tuning inode limit file descriptors tco, kernel etc
  • Variables and Data Types in Shell Scripting
  • Top 10 most used Cat commands with examples (create, view, append files)
  • Ip tables / ufw / firewall d commands for block port ip rate limiting
  • Top 10 zip / tar commands to compress & extract files in linux
  • TOP 10 mv & cp commands in linux to move & copy files in Linux
  • Top 10 GREP Commands in linux to search files directory words strings
  • lsof netstat commands to know listening ports in linux 3 ways
  • Upgrade Ubuntu from 18.04 (19.10) to 20.04 LTS command line or gui server | desktop
  • 3 Ways (SCP, rsync, Sftp) linux server migration between two remote server apache nginx
  • linux system specs commands (CPU, Memory, Disk )speed, type. manufacture
  • linux sysctl command tweaks & hardening
  • linux security limits.conf deciding user limits process limits for nginx server
  • ulimit linux unlimited command unlimto set & know user limits open files file descriptor max user process etc.
  • red hat linux certification cost jobs salary syllabus courses fees
  • ufw firewall commads allow port enable disable ubuntu 20.04
  • ddos attack prevention
  • change ssh port in linux - avoid sshd ddos attacks
  • ping command
  • memcached install ubuntu wordpress
  • check linux version (lsb_release -a) ubuntu debian 32 or 64 bit
  • rsync command linux with examples comparison to scp
  • how to uninstall package in linux ubuntu rpm, yum apt-get
  • increase open file limit linux File descriptor ft nginx , mysql, lemp
  • remove repository ubuntu
  • htop commad memory details virtual vs shard vs resident
  • chown command in Linux with Examples
  • Kill PHP process
  • VIrtual Memory vs RSS Memory vs Shared memory in Linux
  • oom killer fixing it by configuration linux ubuntu
  • Install Lemp nginx mysql php fpm Stack on Debian 11 with repository
  • connect two remote servers linux command line
  • auto start after oom killer Mysql & php fpm nginx etc ubuntu wth systemd or cron job
  • load average Linux 1, 5, 15 min 2,4,8 cores explained
  • Control Structures in Shell Scripting
  • Shell Scripting Roadmap for Beginners to Advanced
  • awk commands with practical examples
  • Shell Scripting Tutorial for Beginners πŸš€
  • find Command in Linux with Examples
  • sed Command in Linux with Examples (Beginner to Advanced)
  • Linux Text processing commands in with Examples
  • linux disk management commands
  • fdisk command in linux with examples
  • how to add a new disk in linux
  • Linux mount Command with Examples
  • fstab options with examples
  • Top 50 Shell Scripting Interview Questions and Answers
  • Linux Networking Interview Questions and Answers
  • Linux Networking Commands Cheat Sheet with Examples pdf
  • Netstat & SS Commands cheat sheet with examples Interview Questions
  • Nmap Cheat Sheet – Network Scanning & Security
  • Bash Brackets ([], (), {}, $( ), $(( ))) – Types, Uses & Examples

hi i am raju ginni, primalry i manage wordpress websites on GCP cloud platform as a cloud engineer, and create content on passionate things.
you can follow me on youtbe

© 2025 - All Rights Reserved Disclaimer & Privacy Policy