Basic Bash Examples
This section contains fundamental Bash scripting examples to help you practice and understand core concepts.
Hello World Variations
Simple Hello World
#!/bin/bash
echo "Hello, World!"Hello World with Variables
#!/bin/bash
name="World"
echo "Hello, $name!"Interactive Hello World
#!/bin/bash
echo "What's your name?"
read name
echo "Hello, $name! Nice to meet you."Hello World with Date
#!/bin/bash
echo "Hello, World!"
echo "Today is: $(date)"
echo "Current user: $(whoami)"Variable Examples
Basic Variable Operations
#!/bin/bash
# Variable assignment
first_name="John"
last_name="Doe"
age=25
# Variable usage
echo "Name: $first_name $last_name"
echo "Age: $age"
# Variable concatenation
full_name="$first_name $last_name"
echo "Full name: $full_name"Environment Variables
#!/bin/bash
echo "Your home directory: $HOME"
echo "Your username: $USER"
echo "Your shell: $SHELL"
echo "Current path: $PATH"Variable Default Values
#!/bin/bash
# Set default values
database_host=${DB_HOST:-"localhost"}
database_port=${DB_PORT:-"5432"}
database_name=${DB_NAME:-"myapp"}
echo "Database configuration:"
echo "Host: $database_host"
echo "Port: $database_port"
echo "Database: $database_name"Variable Length and Manipulation
#!/bin/bash
text="Hello World"
echo "Original text: $text"
echo "Length: ${#text}"
echo "Uppercase: ${text^^}"
echo "Lowercase: ${text,,}"
echo "First 5 characters: ${text:0:5}"
echo "Last 5 characters: ${text: -5}"Command Line Arguments
Basic Argument Handling
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
echo "Number of arguments: $#"Argument Validation
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 <name> [age]"
exit 1
fi
name="$1"
age="${2:-unknown}"
echo "Name: $name"
echo "Age: $age"Processing Multiple Arguments
#!/bin/bash
echo "Processing all arguments:"
for arg in "$@"; do
echo "Argument: $arg"
doneSimple Calculations
Basic Arithmetic
#!/bin/bash
a=10
b=5
echo "a = $a, b = $b"
echo "Addition: $((a + b))"
echo "Subtraction: $((a - b))"
echo "Multiplication: $((a * b))"
echo "Division: $((a / b))"
echo "Modulo: $((a % b))"Calculator Script
#!/bin/bash
echo "Simple Calculator"
read -p "Enter first number: " num1
read -p "Enter operator (+, -, *, /): " op
read -p "Enter second number: " num2
case $op in
+) result=$((num1 + num2)) ;;
-) result=$((num1 - num2)) ;;
\*) result=$((num1 * num2)) ;;
/)
if [ $num2 -eq 0 ]; then
echo "Error: Division by zero"
exit 1
fi
result=$((num1 / num2))
;;
*) echo "Invalid operator"; exit 1 ;;
esac
echo "Result: $num1 $op $num2 = $result"Temperature Converter
#!/bin/bash
echo "Temperature Converter"
echo "1. Celsius to Fahrenheit"
echo "2. Fahrenheit to Celsius"
read -p "Choose option (1 or 2): " choice
case $choice in
1)
read -p "Enter temperature in Celsius: " celsius
fahrenheit=$(echo "scale=2; $celsius * 9/5 + 32" | bc)
echo "$celsius°C = $fahrenheit°F"
;;
2)
read -p "Enter temperature in Fahrenheit: " fahrenheit
celsius=$(echo "scale=2; ($fahrenheit - 32) * 5/9" | bc)
echo "$fahrenheit°F = $celsius°C"
;;
*)
echo "Invalid choice"
exit 1
;;
esacFile Operations
File Information
#!/bin/bash
filename="$1"
if [ -z "$filename" ]; then
echo "Usage: $0 <filename>"
exit 1
fi
if [ -f "$filename" ]; then
echo "File: $filename"
echo "Size: $(stat -c%s "$filename") bytes"
echo "Last modified: $(stat -c%y "$filename")"
echo "Permissions: $(stat -c%A "$filename")"
echo "Owner: $(stat -c%U "$filename")"
echo "Group: $(stat -c%G "$filename")"
else
echo "File '$filename' does not exist"
fiFile Backup
#!/bin/bash
source_file="$1"
if [ -z "$source_file" ]; then
echo "Usage: $0 <source_file>"
exit 1
fi
if [ ! -f "$source_file" ]; then
echo "Error: File '$source_file' does not exist"
exit 1
fi
backup_file="${source_file}.backup.$(date +%Y%m%d_%H%M%S)"
if cp "$source_file" "$backup_file"; then
echo "Backup created: $backup_file"
else
echo "Error: Failed to create backup"
exit 1
fiDirectory Listing
#!/bin/bash
directory="${1:-.}"
echo "Contents of directory: $directory"
echo "=================================="
if [ -d "$directory" ]; then
for item in "$directory"/*; do
if [ -f "$item" ]; then
echo "FILE: $(basename "$item")"
elif [ -d "$item" ]; then
echo "DIR: $(basename "$item")"
fi
done
else
echo "Error: '$directory' is not a directory"
fiText Processing
Word Count
#!/bin/bash
filename="$1"
if [ -z "$filename" ]; then
echo "Usage: $0 <filename>"
exit 1
fi
if [ -f "$filename" ]; then
lines=$(wc -l < "$filename")
words=$(wc -w < "$filename")
chars=$(wc -c < "$filename")
echo "File: $filename"
echo "Lines: $lines"
echo "Words: $words"
echo "Characters: $chars"
else
echo "File '$filename' does not exist"
fiText Search
#!/bin/bash
if [ $# -ne 2 ]; then
echo "Usage: $0 <search_term> <filename>"
exit 1
fi
search_term="$1"
filename="$2"
if [ ! -f "$filename" ]; then
echo "File '$filename' does not exist"
exit 1
fi
echo "Searching for '$search_term' in '$filename':"
grep -n "$search_term" "$filename"
count=$(grep -c "$search_term" "$filename")
echo "Found $count occurrences"Line Numbering
#!/bin/bash
filename="$1"
if [ -z "$filename" ]; then
echo "Usage: $0 <filename>"
exit 1
fi
if [ -f "$filename" ]; then
line_number=1
while IFS= read -r line; do
printf "%3d: %s\n" $line_number "$line"
((line_number++))
done < "$filename"
else
echo "File '$filename' does not exist"
fiSystem Information
System Status
#!/bin/bash
echo "=== System Information ==="
echo "Hostname: $(hostname)"
echo "Uptime: $(uptime -p)"
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo "Date: $(date)"
echo
echo "=== Memory Usage ==="
free -h
echo
echo "=== Disk Usage ==="
df -h
echo
echo "=== CPU Information ==="
lscpu | grep "Model name"Process Monitor
#!/bin/bash
echo "Top 10 processes by CPU usage:"
ps aux --sort=-%cpu | head -11
echo
echo "Top 10 processes by memory usage:"
ps aux --sort=-%mem | head -11Network Information
#!/bin/bash
echo "=== Network Information ==="
echo "Hostname: $(hostname)"
echo "Domain: $(hostname -d 2>/dev/null || echo "Not set")"
echo
echo "=== Network Interfaces ==="
ip addr show | grep -E "^[0-9]+:|inet "
echo
echo "=== Routing Table ==="
ip route showUser Input Examples
User Registration
#!/bin/bash
echo "User Registration Form"
echo "====================="
read -p "First Name: " first_name
read -p "Last Name: " last_name
read -p "Email: " email
read -p "Age: " age
read -s -p "Password: " password
echo
echo
echo "Registration Summary:"
echo "Name: $first_name $last_name"
echo "Email: $email"
echo "Age: $age"
echo "Password: [hidden]"
read -p "Is this information correct? (y/n): " confirm
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
echo "Registration completed!"
else
echo "Registration cancelled."
fiQuiz Game
#!/bin/bash
score=0
total_questions=3
echo "Welcome to the Bash Quiz!"
echo "========================"
# Question 1
echo "Question 1: What command shows the current directory?"
echo "a) pwd"
echo "b) cd"
echo "c) ls"
read -p "Your answer: " answer1
if [ "$answer1" = "a" ] || [ "$answer1" = "A" ]; then
echo "Correct!"
((score++))
else
echo "Wrong! The correct answer is 'a) pwd'"
fi
# Question 2
echo
echo "Question 2: What symbol is used for comments in bash?"
echo "a) //"
echo "b) #"
echo "c) /*"
read -p "Your answer: " answer2
if [ "$answer2" = "b" ] || [ "$answer2" = "B" ]; then
echo "Correct!"
((score++))
else
echo "Wrong! The correct answer is 'b) #'"
fi
# Question 3
echo
echo "Question 3: What command lists files and directories?"
echo "a) list"
echo "b) dir"
echo "c) ls"
read -p "Your answer: " answer3
if [ "$answer3" = "c" ] || [ "$answer3" = "C" ]; then
echo "Correct!"
((score++))
else
echo "Wrong! The correct answer is 'c) ls'"
fi
echo
echo "Quiz completed!"
echo "Your score: $score out of $total_questions"
percentage=$((score * 100 / total_questions))
if [ $percentage -ge 80 ]; then
echo "Excellent work!"
elif [ $percentage -ge 60 ]; then
echo "Good job!"
else
echo "Keep practicing!"
fiString Manipulation
String Operations
#!/bin/bash
text="Hello World Programming"
echo "Original: $text"
echo "Length: ${#text}"
echo "Uppercase: ${text^^}"
echo "Lowercase: ${text,,}"
echo "First word: ${text%% *}"
echo "Last word: ${text##* }"
echo "Remove 'Hello': ${text/Hello/}"
echo "Replace 'World' with 'Bash': ${text/World/Bash}"
echo "First 10 chars: ${text:0:10}"
echo "From position 6: ${text:6}"Palindrome Checker
#!/bin/bash
read -p "Enter a word to check if it's a palindrome: " word
# Convert to lowercase and remove spaces
clean_word=$(echo "$word" | tr '[:upper:]' '[:lower:]' | tr -d ' ')
# Reverse the string
reversed=$(echo "$clean_word" | rev)
if [ "$clean_word" = "$reversed" ]; then
echo "'$word' is a palindrome!"
else
echo "'$word' is not a palindrome."
fiPassword Generator
#!/bin/bash
read -p "Enter password length (default 12): " length
length=${length:-12}
# Generate password using /dev/urandom
password=$(tr -dc 'A-Za-z0-9!@#$%^&*' < /dev/urandom | head -c "$length")
echo "Generated password: $password"
echo "Password strength:"
echo "Length: $length characters"
# Check password strength
if [[ $password =~ [A-Z] ]]; then
echo "✓ Contains uppercase letters"
fi
if [[ $password =~ [a-z] ]]; then
echo "✓ Contains lowercase letters"
fi
if [[ $password =~ [0-9] ]]; then
echo "✓ Contains numbers"
fi
if [[ $password =~ [!@#\$%\^&\*] ]]; then
echo "✓ Contains special characters"
fiArray Examples
Basic Array Operations
#!/bin/bash
# Create array
fruits=("apple" "banana" "orange" "grape")
echo "All fruits: ${fruits[@]}"
echo "Number of fruits: ${#fruits[@]}"
echo "First fruit: ${fruits[0]}"
echo "Last fruit: ${fruits[-1]}"
# Add element
fruits+=("mango")
echo "After adding mango: ${fruits[@]}"
# Loop through array
echo "Fruits list:"
for i in "${!fruits[@]}"; do
echo "$((i+1)). ${fruits[i]}"
doneShopping List
#!/bin/bash
declare -a shopping_list
echo "Shopping List Manager"
echo "===================="
while true; do
echo
echo "1. Add item"
echo "2. Remove item"
echo "3. Show list"
echo "4. Clear list"
echo "5. Exit"
read -p "Choose option: " choice
case $choice in
1)
read -p "Enter item to add: " item
shopping_list+=("$item")
echo "Added '$item' to the list"
;;
2)
if [ ${#shopping_list[@]} -eq 0 ]; then
echo "List is empty"
else
echo "Current items:"
for i in "${!shopping_list[@]}"; do
echo "$((i+1)). ${shopping_list[i]}"
done
read -p "Enter item number to remove: " num
if [ "$num" -ge 1 ] && [ "$num" -le ${#shopping_list[@]} ]; then
removed_item="${shopping_list[$((num-1))]}"
unset shopping_list[$((num-1))]
shopping_list=("${shopping_list[@]}") # Re-index array
echo "Removed '$removed_item'"
else
echo "Invalid item number"
fi
fi
;;
3)
if [ ${#shopping_list[@]} -eq 0 ]; then
echo "Shopping list is empty"
else
echo "Shopping List:"
for i in "${!shopping_list[@]}"; do
echo "$((i+1)). ${shopping_list[i]}"
done
fi
;;
4)
shopping_list=()
echo "List cleared"
;;
5)
echo "Goodbye!"
exit 0
;;
*)
echo "Invalid choice"
;;
esac
doneGrade Calculator
#!/bin/bash
declare -a grades
declare -a subjects
echo "Grade Calculator"
echo "==============="
read -p "How many subjects? " num_subjects
for ((i=1; i<=num_subjects; i++)); do
read -p "Enter subject $i name: " subject
read -p "Enter grade for $subject: " grade
subjects+=("$subject")
grades+=("$grade")
done
# Calculate average
total=0
for grade in "${grades[@]}"; do
total=$((total + grade))
done
average=$((total / num_subjects))
echo
echo "Grade Report:"
echo "============"
for i in "${!subjects[@]}"; do
echo "${subjects[i]}: ${grades[i]}"
done
echo
echo "Average: $average"
if [ $average -ge 90 ]; then
echo "Grade: A (Excellent)"
elif [ $average -ge 80 ]; then
echo "Grade: B (Good)"
elif [ $average -ge 70 ]; then
echo "Grade: C (Average)"
elif [ $average -ge 60 ]; then
echo "Grade: D (Below Average)"
else
echo "Grade: F (Fail)"
fi