Bash Scripting Basics: A Beginner's Guide
Bash scripting automates repetitive tasks on Linux. Here’s everything a beginner needs to know.
Your First Script
#!/bin/bash
echo "Hello, World!"Save as hello.sh, then:
chmod +x hello.sh
./hello.shThe first line (#!/bin/bash) is the shebang — it tells the system which interpreter to use.
Variables
#!/bin/bash
# Assigning variables (no spaces around =)
name="Alice"
age=30
# Using variables (use quotes to handle spaces)
echo "$name is $age years old"
# Command substitution
files=$(ls)
echo "Files in current directory: $files"
# User input
read -p "Enter your name: " username
echo "Hello, $username"Conditionals
#!/bin/bash
# If-else
if [ "$1" = "hello" ]; then
echo "Hello to you too!"
elif [ "$1" = "bye" ]; then
echo "Goodbye!"
else
echo "I don't understand"
fi
# File checks
if [ -f "/etc/passwd" ]; then
echo "File exists"
fi
if [ -d "/home/user" ]; then
echo "Directory exists"
fi
# Numeric comparisons
count=5
if [ "$count" -gt 3 ]; then
echo "Count is greater than 3"
fiComparison operators:
| Operator | Meaning |
|---|---|
-eq | Equal |
-ne | Not equal |
-gt | Greater than |
-lt | Less than |
-z | String is empty |
-n | String is not empty |
Loops
#!/bin/bash
# For loop over a list
for name in Alice Bob Charlie; do
echo "Hello, $name"
done
# For loop with range
for i in {1..5}; do
echo "Number: $i"
done
# While loop
count=1
while [ "$count" -le 5 ]; do
echo "Count: $count"
((count++))
done
# Loop over files
for file in *.txt; do
echo "Processing $file"
doneFunctions
#!/bin/bash
# Define a function
greet() {
local name="$1" # $1 is the first argument
echo "Hello, $name!"
}
# Function with return value
add() {
local sum=$(( $1 + $2 ))
echo "$sum" # Use echo to "return" a value
}
# Call functions
greet "Alice"
result=$(add 5 3)
echo "5 + 3 = $result"Arguments and Special Variables
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
echo "Number of arguments: $#"
echo "Exit status of last command: $?"
echo "Process ID: $$"Reading Files
#!/bin/bash
# Line by line
while IFS= read -r line; do
echo "Line: $line"
done < "input.txt"
# Read CSV
while IFS=',' read -r name age city; do
echo "$name is $age years old and lives in $city"
done < "data.csv"Error Handling
#!/bin/bash
# Exit on error
set -e
# Exit on undefined variable
set -u
# Print commands before executing (debug mode)
set -x
# Check exit status
if ! mkdir "/backup"; then
echo "Error: Could not create backup directory"
exit 1
fiReal-World Examples
Backup Script
#!/bin/bash
BACKUP_DIR="/backup/$(date +%Y-%m-%d)"
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/home.tar.gz" /home/user
tar -czf "$BACKUP_DIR/etc.tar.gz" /etc
echo "Backup completed: $BACKUP_DIR"Log Rotation
#!/bin/bash
LOG_FILE="/var/log/app.log"
MAX_SIZE=10485760 # 10MB in bytes
file_size=$(stat -f%z "$LOG_FILE" 2>/dev/null || stat --printf="%s" "$LOG_FILE" 2>/dev/null)
if [ "$file_size" -gt "$MAX_SIZE" ]; then
mv "$LOG_FILE" "$LOG_FILE.$(date +%Y%m%d-%H%M%S)"
touch "$LOG_FILE"
echo "Log rotated"
fiRelated: See our Linux command cheat sheet and cron jobs guide.