Skip to main content

Linux Shell Scripting

Automate repetitive tasks and build powerful scripts with Bash.

Basic Script Structure

#!/bin/bash
# This is a comment

echo "Hello, World!"

Variables

#!/bin/bash

NAME="John"
AGE=30

echo "Name: $NAME"
echo "Age: $AGE"

# Command substitution
CURRENT_DIR=$(pwd)
DATE=$(date +%Y-%m-%d)

Conditionals

#!/bin/bash

if [ "$1" == "start" ]; then
    echo "Starting..."
elif [ "$1" == "stop" ]; then
    echo "Stopping..."
else
    echo "Usage: $0 {start|stop}"
fi

Loops

#!/bin/bash

# For loop
for i in {1..5}; do
    echo "Number: $i"
done

# While loop
counter=1
while [ $counter -le 5 ]; do
    echo "Count: $counter"
    ((counter++))
done

# Loop through files
for file in *.txt; do
    echo "Processing: $file"
done

Functions

#!/bin/bash

greet() {
    echo "Hello, $1!"
}

greet "Alice"
greet "Bob"

Cron Jobs

# Edit crontab
crontab -e

# Run script every day at 2 AM
0 2 * * * /path/to/script.sh

# Run every 5 minutes
*/5 * * * * /path/to/script.sh

# View cron jobs
crontab -l

🎉 Congratulations! You’ve completed the Linux Crash Course. Next: Docker Crash Course →