Introduction to Shell Scripting

What You'll Learn

A shell script is a text file containing a sequence of commands that the terminal runs one after another. Scripts automate repetitive tasks — backups, deployments, system checks, and more.

Your First Script

nano hello.sh

Type this content:

#!/bin/bash
# My first script
echo "Hello, LinuxTrix!"
echo "Today is: $(date)"
echo "You are logged in as: $(whoami)"

The first line (#!/bin/bash) is called a shebang. It tells the system to use Bash to run this script.

Making It Executable and Running It

chmod +x hello.sh         # Make it executable
./hello.sh                # Run it

Variables

# Define variables (no spaces around =)
NAME="Alex"
GREETING="Hello, $NAME!"

# Use them with $
echo $GREETING

# Special variables
echo $0       # Script name
echo $1       # First argument passed to the script
echo $#       # Number of arguments

Example: A Greeting Script

#!/bin/bash
NAME=$1
if [ -z "$NAME" ]; then
    echo "Usage: $0 <name>"
else
    echo "Hello, $NAME! Welcome to LinuxTrix."
fi
# Run with: ./greet.sh Alex

If/Else Conditionals

#!/bin/bash
FILE="/etc/hostname"
if [ -f "$FILE" ]; then
    echo "$FILE exists."
elif [ -d "$FILE" ]; then
    echo "$FILE is a directory."
else
    echo "$FILE does not exist."
fi

Common Test Conditions

-f fileTrue if file exists and is a regular file
-d dirTrue if it's a directory
-z stringTrue if string is empty
-n stringTrue if string is not empty
str1 = str2True if strings are equal

Loops

For Loop

#!/bin/bash
for FILE in *.txt; do
    echo "Found: $FILE"
done

While Loop

#!/bin/bash
COUNTER=1
while [ $COUNTER -le 5 ]; do
    echo "Count: $COUNTER"
    COUNTER=$((COUNTER + 1))
done

Useful Script Ideas for Beginners

Disk Usage Report

#!/bin/bash
echo "=== Disk Usage Report ==="
df -h
echo ""
echo "=== Top 10 Largest Files in /var ==="
find /var -type f -exec du -sh {} + | sort -rh | head -10

Backup Script

#!/bin/bash
BACKUP_DIR="/backups/$(date +%Y%m%d)"
mkdir -p "$BACKUP_DIR"
tar -czvf "$BACKUP_DIR/home-backup.tar.gz" /home/
echo "Backup saved to $BACKUP_DIR"

Practice Exercise

# Create a script that:
# 1. Asks for your name (read -p "Name? " NAME)
# 2. Creates a folder named after you in ~/projects/
# 3. Creates an index.html file inside it
# 4. Reports what it did

Troubleshooting

What's Next?

You can automate tasks — now learn how to monitor your system and read logs:

System Monitoring & Logs →