Skip to content

Shell Scripting Masterclass 🌟

Mahesh Shukla edited this page Sep 2, 2025 · 1 revision

Introduction

Shell scripting is the backbone of automation in Unix/Linux environments. This wiki is designed to teach everything you need to become a master of Shell scripting, from basics to advanced automation, in a structured, easy-to-follow way.


Table of Contents


Variables πŸ“

πŸ”Ή Basics of Variables
  • Variables are containers for data.
  • Syntax: variable_name=value (no spaces around =)
  • Access: $variable_name
name="Mahesh"
echo "Hello, $name"
  • Read-only variables: readonly VAR or declare -r VAR
  • Unsetting variables: unset VAR
πŸ”Ή Types of Variables
  • Local Variables: Exist within a script/function

  • Environment Variables: Available to sub-processes (export VAR=value)

  • Special Variables:

    • $0 : script name
    • $1..$9 : positional parameters
    • $# : number of arguments
    • $@ : all arguments
    • $? : exit status of last command
    • $$ : process ID of current shell
    • $! : PID of last background process

Conditionals 🧩

πŸ”Ή if-else
#!/bin/bash
num=10
if [ $num -gt 5 ]; then
    echo "Number is greater than 5"
else
    echo "Number is 5 or less"
fi
  • [ ] : POSIX test command
  • [[ ]] : enhanced test with regex and pattern matching
πŸ”Ή case Statement
#!/bin/bash
fruit="apple"
case $fruit in
    "apple") echo "Red Fruit";;
    "banana") echo "Yellow Fruit";;
    *) echo "Unknown Fruit";;
esac

Loops πŸ”„

πŸ”Ή for Loop
for i in 1 2 3 4 5; do
    echo "Number $i"
done
  • C-style for loop:
for ((i=0; i<5; i++)); do
    echo $i
done
πŸ”Ή while Loop
count=1
while [ $count -le 5 ]; do
    echo $count
    ((count++))
done
πŸ”Ή until Loop
count=1
until [ $count -gt 5 ]; do
    echo $count
    ((count++))
done

Functions βš™οΈ

πŸ”Ή Basic Functions
my_function() {
    echo "Hello World"
}

my_function
  • Return values: use return or echo
  • Parameters: $1, $2...
sum() {
    result=$(($1 + $2))
    echo $result
}

sum 5 10  # prints 15

Arrays & Strings πŸ“¦

πŸ”Ή Arrays
arr=(one two three)
echo ${arr[0]}  # one
arr+=(four)
echo ${arr[@]}  # one two three four
πŸ”Ή String Operations
str="Hello World"
echo ${#str}   # length
echo ${str:6:5} # substring

Input/Output & Redirection πŸ“₯πŸ“€

πŸ”Ή Redirection
  • > : overwrite output to file
  • >> : append output to file
  • < : input from file
  • | : pipe output to next command
ls > filelist.txt
cat filelist.txt | grep ".txt"
πŸ”Ή Read Input
read -p "Enter your name: " name
echo "Hello $name"

Automation & Cron Jobs ⏱️

πŸ”Ή Cron Jobs
  • Edit cron jobs: crontab -e
  • Format: * * * * * /path/to/script
# Run backup.sh every day at 2 AM
0 2 * * * /home/user/backup.sh

Error Handling & Debugging 🐞

πŸ”Ή Debugging
  • Run script in debug mode: bash -x script.sh
  • Stop on error: set -e
  • Trap errors:
trap 'echo Error on line $LINENO' ERR

Practical Scripts πŸ’»

πŸ”Ή Backup Script
#!/bin/bash
# Daily Backup
src="/home/user/data"
dest="/home/user/backup"
date=$(date +%F)
mkdir -p $dest/$date
cp -r $src/* $dest/$date/
echo "Backup completed for $date"
πŸ”Ή System Info Script
#!/bin/bash
echo "CPU Info:"
lscpu
echo "Memory Info:"
free -h
echo "Disk Usage:"
df -h
πŸ”Ή User Management Script
#!/bin/bash
# Add new user
echo -n "Enter username: "
read username
sudo useradd $username
sudo passwd $username
echo "User $username added successfully"

Best Practices & Strategy 🌟

πŸ”Ή Learning Strategy
  1. Start Small: Write simple scripts to automate repetitive tasks.
  2. Understand Variables & Conditionals before loops.
  3. Break Problems into Functions for reusability.
  4. Practice Logging & Debugging to catch errors early.
  5. Gradually Learn Automation: cron jobs, backups, monitoring.
  6. Read Scripts from Others: learn professional conventions.
  7. Document Everything: Comments and README for scripts.

Conclusion βœ…

This wiki provides a complete roadmap to master shell scripting from scratch. By following examples, practicing scripts, and implementing automation, you can reach top 0.1% proficiency.

Happy Scripting! πŸš€