1. Introduction to Bash Scripting
What is Bash?
- Bash (Bourne Again SHell) is a command-line interpreter that allows you to run commands in Unix-like operating systems.
- Scripts are files containing a series of commands that the shell can execute.
2. Basic Concepts
Shebang (#!
)
- The shebang (
#!
) at the top of a script specifies the interpreter that should be used to run the script.
#!/bin/bash
echo "Hello, World!"
Creating and Running a Script
- Create a Script File: Use a text editor to create a new file, e.g.,
hello.sh
.
nano hello.sh
2.Add Executable Permissions: Make the script executable
chmod +x hello.sh
3. Edit the Script File: Add commands to the script
#!/bin/bash
echo "Hello, World!"
4. Run the Script: Execute the script.
./hello.sh
3. Variables and Data Types
Declaring Variables
- Variables are used to store data.
name="John"
echo "Hello, $name"
Arithmetic Operations
- Perform arithmetic using
$((...))
.
num1=5
num2=3
sum=$((num1 + num2))
echo "Sum: $sum"
4. Control Structures
Conditional Statements
if
statement:
#!/bin/bash
num=10
if [ $num -gt 5 ]; then
echo "The number is greater than 5"
fi
if-else
statement:
#!/bin/bash
num=3
if [ $num -gt 5 ]; then
echo "The number is greater than 5"
else
echo "The number is not greater than 5"
fi
Loops
for
loop:
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
while
loop:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
5. Functions
Defining and Calling Functions
- Define a function:
#!/bin/bash
greet() {
echo "Hello, $1"
}
greet "World"
Passing Arguments to Functions
- Functions can take arguments
#!/bin/bash
add() {
sum=$(( $1 + $2 ))
echo "Sum: $sum"
}
add 3 4
6. Advanced Concepts
Arrays
- Arrays store multiple values
#!/bin/bash
fruits=("Apple" "Banana" "Cherry")
echo "First fruit: ${fruits[0]}"
echo "All fruits: ${fruits[@]}"
File Operations
- Reading from a file:
#!/bin/bash
while IFS= read -r line; do
echo "$line"
done < "file.txt"
Writing to a file:
#!/bin/bash
echo "Hello, File!" > output.txt
Error Handling
- Using
exit
to exit a script with a status
#!/bin/bash
if [ -z "$1" ]; then
echo "No argument provided"
exit 1
fi
echo "Argument: $1"
Debugging
- Enable debugging mode:
#!/bin/bash
set -x
echo "Debug mode enabled"
set +x
echo "Debug mode disabled"
7. Scripting Best Practices
Commenting
- Use comments to explain your code
#!/bin/bash
# This script prints a greeting message
echo "Hello, World!"
Code Organization
- Use functions and organize code into logical sections
#!/bin/bash
greet() {
echo "Hello, $1"
}
greet "Alice"
greet "Bob"
Security Considerations
- Validate user inputs to prevent security issues
#!/bin/bash
read -p "Enter a number: " num
if ! [[ "$num" =~ ^[0-9]+$ ]]; then
echo "Invalid input"
exit 1
fi
echo "You entered: $num"
Example Scripts
- Basic Script
#!/bin/bash
echo "Hello, World!"
2.Advanced Script: Backup Script
#!/bin/bash
backup_files="/home/user/docs"
dest="/home/user/backup"
date=$(date +%Y-%m-%d)
hostname=$(hostname -s)
archive_file="$hostname-$date.tgz"
echo "Backing up $backup_files to $dest/$archive_file"
tar czf $dest/$archive_file $backup_files
Some of Important and useful script
1. System Monitoring Script
CPU and Memory Usage
#!/bin/bash
echo "CPU and Memory Usage:"
echo "====================="
echo "CPU Load:"
uptime
echo ""
echo "Memory Usage:"
free -h
echo ""
Disk Usage Monitoring
#!/bin/bash
echo "Disk Usage:"
echo "==========="
df -h
echo ""
2. File Management Scripts
Backup Script
#!/bin/bash
# Variables
backup_source="/home/user/docs"
backup_dest="/home/user/backup"
date=$(date +%Y-%m-%d)
backup_file="$backup_dest/backup-$date.tar.gz"
# Create a backup
echo "Creating backup of $backup_source at $backup_file"
tar -czvf $backup_file $backup_source
echo "Backup completed."
Cleanup Script
#!/bin/bash
# Directory to clean up
cleanup_dir="/tmp"
# Find and delete files older than 7 days
echo "Cleaning up files older than 7 days in $cleanup_dir"
find $cleanup_dir -type f -mtime +7 -exec rm -f {} \;
echo "Cleanup completed."
3. User Management Scripts
Add User Script
#!/bin/bash
# Check if user is root
if [ $(id -u) -ne 0 ]; then
echo "You must be root to add a user."
exit 1
fi
# Read username
read -p "Enter username: " username
# Add user
useradd -m $username
# Set password
passwd $username
echo "User $username has been added to the system."
Delete User Script
#!/bin/bash
# Check if user is root
if [ $(id -u) -ne 0 ]; then
echo "You must be root to delete a user."
exit 1
fi
# Read username
read -p "Enter username to delete: " username
# Delete user
userdel -r $username
echo "User $username has been deleted from the system."
4. Network Management Scripts
Check Network Connectivity
#!/bin/bash
# Check connectivity to Google
echo "Checking connectivity to Google..."
ping -c 4 google.com
# Check connectivity to a local server
local_server="192.168.1.1"
echo "Checking connectivity to local server ($local_server)..."
ping -c 4 $local_server
Network Interface Details
#!/bin/bash
# List network interfaces and their IP addresses
echo "Network Interfaces and IP Addresses:"
ip -brief address
5. System Update and Maintenance Scripts
Update System Script
#!/bin/bash
# Update package lists
echo "Updating package lists..."
sudo apt update
# Upgrade all packages
echo "Upgrading all packages..."
sudo apt upgrade -y
echo "System update completed."
Check for Security Updates
#!/bin/bash
# List available security updates
echo "Checking for security updates..."
sudo apt list --upgradable | grep -i security
6. Automation and Scheduling Scripts
Cron Job Setup Script
#!/bin/bash
# Add a cron job to run a script every day at midnight
cron_job="0 0 * * * /path/to/your/script.sh"
# Check if the cron job already exists
(crontab -l | grep -q "$cron_job") && echo "Cron job already exists." || (crontab -l; echo "$cron_job") | crontab -
echo "Cron job setup completed."
7. Advanced Scripts
Process Monitoring Script
#!/bin/bash
# Monitor a specific process by name
process_name="apache2"
if pgrep $process_name > /dev/null
then
echo "$process_name is running"
else
echo "$process_name is not running"
fi
Log Rotation Script
#!/bin/bash
# Log directory
log_dir="/var/log/myapp"
# Rotate logs older than 7 days
find $log_dir -type f -mtime +7 -exec gzip {} \;
echo "Log rotation completed."
8. Backup Database Script
MySQL Database Backup
#!/bin/bash
# Variables
db_user="root"
db_password="yourpassword"
db_name="mydatabase"
backup_dir="/home/user/db_backup"
date=$(date +%Y-%m-%d)
backup_file="$backup_dir/$db_name-$date.sql"
# Create a backup
echo "Backing up database $db_name to $backup_file"
mysqldump -u $db_user -p$db_password $db_name > $backup_file
echo "Backup completed."
Comparison Operators
Numeric Comparisons
-eq
: equal to-ne
: not equal to-lt
: less than-le
: less than or equal to-gt
: greater than-ge
: greater than or equal to
String Comparisons
=
: equal to!=
: not equal to<
: less than (in ASCII alphabetical order)>
: greater than (in ASCII alphabetical order)-z
: string is null (has zero length)-n
: string is not null (has non-zero length)
Combining Conditions
You can also combine conditions using logical operators:
&&
: logical AND||
: logical OR