COURSE ยท 7 LESSONS ยท 100% FREE
๐Ÿš

Bash / Shell Scripting

The Unix command line. Automate tasks, parse text, manage systems. Every developer needs shell skills.

0Lessons
0Code Examples
ZeroPrerequisites
0%
You've completed 0 of 7 lessons
J/โ†“ Next
K/โ†‘ Prev
Esc Collapse
/ Search
Foundations
01

Hello World & Setup

#!/bin/bash shebang. echo for output. Variables with $name. Run: bash file.sh

๐Ÿง  Note for the confused:
Bash is talking to your computer in grunts and gestures. No fancy GUI. Just you, a terminal, and a blinking cursor that judges your life choices. Welcome to the big leagues.
#!/bin/bash
echo "Hello, World!"

# Variables
NAME="Mayank"
AGE=15
echo "$NAME is $AGE"
echo "${NAME}'s age is $AGE"

# Read input
read -p "Enter name: " INPUT
echo "Hello, $INPUT!"

# Run: chmod +x script.sh && ./script.sh
# Or: bash script.sh
02

Variables & Data Types

Everything is a string. Arrays, env vars, special vars ($?, $#, $$, $@).

๐Ÿง  Note for the confused:
Variables in Bash are like sticky notes. You write 'NAME=Mayank' and then use '$NAME' to read it. No spaces around '=' because Bash is dramatic and will break if you breathe wrong.
#!/bin/bash

# Strings
NAME="Mayank"
echo "Length: ${#NAME}"           # 6
echo "Substring: ${NAME:0:3}"     # May
echo "Uppercase: ${NAME^^}"       # MAYANK

# Arrays
LANGS=(Python Go Rust Bash)
echo "First: ${LANGS[0]}"         # Python
echo "All: ${LANGS[@]}"          # all
echo "Count: ${#LANGS[@]}"       # 4
LANGS+=(Java)  # append

# Env vars
echo "Home: $HOME"
echo "User: $USER"
echo "Path: $PATH"

# Special variables
echo "Exit code: $?"    # last command exit code
echo "Args count: $#"   # number of arguments
echo "PID: $$"          # process ID
echo "All args: $@"     # all arguments
03

Control Flow

if/elif/else/fi, case/esac, for/while/until. Test with [[ ]].

๐Ÿง  Note for the confused:
if/else in Bash uses square brackets '[' ']' with spaces. MISS A SPACE AND BASH SCREAMS. It's like trying to perform surgery while wearing boxing gloves. You'll get there, but it won't be pretty.
#!/bin/bash

SCORE=85
if [[ $SCORE -ge 90 ]]; then
    echo "A"
elif [[ $SCORE -ge 80 ]]; then
    echo "B"
else
    echo "C"
fi

# Case
DAY="mon"
case $DAY in
    mon|tue|wed|thu|fri) echo "Weekday" ;;
    sat|sun) echo "Weekend" ;;
    *) echo "Invalid" ;;
esac

# For loop
for i in {1..5}; do echo $i; done
for file in *.txt; do echo $file; done

# While
N=0
while [[ $N -lt 5 ]]; do
    echo $N
    ((N++))
done

# File test
if [[ -f "/etc/passwd" ]]; then echo "exists"; fi
if [[ -d "/tmp" ]]; then echo "is dir"; fi
if [[ -r "file.txt" ]]; then echo "readable"; fi
04

Functions

function name { } or name() { }. Local vars. Return codes. Arguments.

๐Ÿง  Note for the confused:
For loops in Bash are for doing the same thing multiple times. 'for file in *.txt do echo $file done'. Say it with a country accent. It helps.
#!/bin/bash

# Function
greet() {
    local name=$1
    echo "Hello, $name!"
}

greet "Mayank"

# Return value
calculate() {
    local a=$1
    local b=$2
    echo $((a + b))  # output, not return
}

RESULT=$(calculate 3 4)
echo "3 + 4 = $RESULT"

# Return code
is_even() {
    if [[ $(($1 % 2)) -eq 0 ]]; then
        return 0  # true
    else
        return 1  # false
    fi
}

if is_even 4; then echo "even"; fi

# Arguments
echo "Script: $0"
echo "Arg1: $1"
echo "Arg2: $2"
echo "All: $@"
Advanced
05

Pipes & Redirection

| pipe output to next command. > write, >> append, < input, 2> errors.

๐Ÿง  Note for the confused:
Functions in Bash are like tiny scripts you can call anytime. 'function hello { echo "Hi!"; }' then just type 'hello'. It's like having a magic word that makes the computer say hi.
#!/bin/bash

# Pipe
cat /etc/passwd | grep "/bin/bash" | wc -l

# Redirect
ls > files.txt         # write
ls >> files.txt        # append
sort < unsorted.txt    # input
command 2> errors.txt  # stderr
command > out.txt 2>&1  # both

# Here document
cat << EOF
Hello
World
$NAME
EOF

# Here string
grep "hello" <<< "hello world"

# Process substitution
diff <(ls dir1) <(ls dir2)

# Useful pipes
ps aux | grep nginx | awk '{print $2}' | xargs kill -9
cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -10
06

Text Processing

awk, sed, grep, cut, sort, uniq, tr. The Unix text processing toolkit.

๐Ÿง  Note for the confused:
grep is the 'find my keys' command of the terminal. 'grep error log.txt' = 'computer, find where it says error in this file.' It's like Ctrl+F but way more attitude.
#!/bin/bash

# Grep
grep -r "error" /var/log/
grep -i "hello" file.txt
grep -n "pattern" file.txt
grep -c "pattern" file.txt
grep -v "exclude" file.txt

# AWK
awk '{print $1, $3}' file.txt
cat data.csv | awk -F',' '{sum+=$3} END {print sum}'
awk '$3 > 100 {print $0}' data.txt

# Sed
sed 's/old/new/g' file.txt           # replace in memory
sed -i 's/old/new/g' file.txt        # replace in file
sed -n '10,20p' file.txt             # print lines 10-20
sed '/^#/d' config.txt               # remove comments

# Cut
cut -d',' -f1,3 data.csv           # columns 1 and 3

# Sort & Uniq
sort file.txt | uniq -c | sort -rn   # frequency count

# Tr
tr 'a-z' 'A-Z' < file.txt           # lowercase to upper
echo "hello" | tr -d 'l'            # remove chars
07

Cron & Automation

Schedule tasks with crontab. Automate backups, monitoring, deployments.

๐Ÿง  Note for the confused:
Pipes '|' are like assembly lines. You take the output of one command and feed it to the next. 'ls | grep txt' = 'show me files, then only give me the txt ones.' It's the closest you'll get to feeling like a factory worker.
#!/bin/bash

# Crontab format:
# minute hour day month weekday command
# */5 * * * * /path/to/script.sh    # every 5 min
# 0 2 * * * /path/to/backup.sh      # daily at 2am
# 0 0 * * 0 /path/to/weekly.sh      # every Sunday

# Backup script
DATE=$(date +%Y%m%d)
tar -czf "/backups/db_$DATE.tar.gz" /var/lib/mysql/
find /backups -name "*.tar.gz" -mtime +30 -delete

# System monitoring
#!/bin/bash
CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}')
MEM=$(free | awk '/Mem/{printf "%.1f", $3/$2*100}')
DISK=$(df -h / | awk 'NR==2{print $5}')

if (( $(echo "$CPU > 90" | bc -l) )); then
    echo "High CPU: $CPU%" | mail -s "Alert" admin@test.com
fi

# Auto-deploy
#!/bin/bash
cd /var/www/app
git pull origin main
npm install --production
pm2 restart all
echo "Deployed at $(date)" >> /var/log/deploy.log