Shell Scripting Variables – Complete Beginner Tutorial


Learn how to declare, access, and use variables in Bash with real-world examples.

5.1) Variables

Create a Variable


name="Muni"
echo $name

Environment Variable


export PATH=/usr/local/bin:$PATH

Read Input


echo "Enter your name:"
read username
echo "Welcome $username"

Command Substitution


today=$(date)
echo "Today is: $today"

5.2) Loops (for, while)

For Loop Example


for i in 1 2 3 4 5
do
echo "Number: $i"
done

For Loop – Files in Directory


for file in *.log
do
echo "Processing $file"
done

While Loop


count=1
while [ $count -le 5 ]
do
echo "Count: $count"
count=$((count+1))
done

Infinite While Loop


while true
do
echo "Running..."
sleep 2
done

5.3) If-Else Conditions

Basic If


num=10
if [ $num -gt 5 ]; then
echo "Greater than 5"
fi

If-Else


if [ -f /etc/passwd ]; then
echo "File exists"
else
echo "File does not exist"
fi

Elif


read -p "Enter score: " score
if [ $score -ge 90 ]; then
echo "Grade A"
elif [ $score -ge 60 ]; then
echo "Grade B"
else
echo "Fail"
fi

5.4) Functions

Simple Function


welcome() {
echo "Welcome to Shell Scripting!"
}
welcome

Function with Parameters


add() {
echo "Sum = $(($1 + $2))"
}
add 5 10

Return Values


check_user() {
id $1 > /dev/null 2>&1
return $?
}
check_user muni
echo "Exit status: $?"

5.5) Arrays

Create Array


fruits=("apple" "banana" "orange")

Print Single Element


echo ${fruits[1]}

Print All


echo ${fruits[@]}

Array Loop


for item in ${fruits[@]}
do
echo $item
done

5.6) Automation Scripts

A) User Creation Automation


#!/bin/bash
for user in user1 user2 user3
do
useradd $user
echo "User $user created"
done

B) Backup Automation Script


#!/bin/bash
src="/var/www"
dst="/backup/www-$(date +%F).tar.gz"

tar -czf $dst $src
echo "Backup completed: $dst"

C) Service Monitoring Script


#!/bin/bash
service=httpd

if systemctl is-active --quiet $service; then
echo "$service is running"
else
systemctl start $service
echo "$service restarted"
fi

5.7) Log Monitoring Scripts

A) Real-Time Error Watcher


#!/bin/bash
tail -Fn0 /var/log/messages | \
while read line
do
echo "$line" | grep -i "error" && echo "Error detected!"
done

B) Apache Log Monitor


#!/bin/bash
log="/var/log/httpd/access.log"

grep "$(date +%d/%b/%Y)" $log | wc -l

C) Detect Failed SSH Logins


grep "Failed password" /var/log/secure

5.8) Cron-Based Script Execution

Edit Crontab


crontab -e

Run Script Every Day at 7 PM


0 19 * * * /scripts/backup.sh

Run Script Every 5 Minutes


*/5 * * * * /scripts/monitor.sh

Log Cron Output


0 1 * * * /scripts/cleanup.sh >> /var/log/cleanup.log 2>&1