Bash scripting is a game-changer for IT support teams. It helps automate repetitive tasks, saving time and reducing errors. If you’re working in IT, here’s a single script that automates multiple essential tasks.
Complete Bash Automation Script
#!/bin/bash
# Function to create a new user
create_user() {
read -p "Enter username: " username
sudo useradd -m $username
echo "User $username created."
sudo passwd $username
}
# Function to create multiple users from a file
bulk_create_users() {
while read user; do sudo useradd -m "$user"; done < users.txt
}
# Function to update system and install essential packages
update_system() {
echo "Updating system..."
if [[ -f /usr/bin/apt ]]; then
sudo apt update && sudo apt upgrade -y
sudo apt install -y vim curl wget git
elif [[ -f /usr/bin/yum ]]; then
sudo yum update -y
fi
}
# Function to perform automated backups
backup_system() {
echo "Performing backup..."
tar -czf /backup/home_$(date +%F).tar.gz /home/
}
# Function to clean up logs
cleanup_logs() {
echo "Cleaning up logs..."
find /var/log -name "*.log" -mtime +7 -exec rm {} \;
}
# Function to check system health
system_health_check() {
echo "Checking system health..."
df -h
free -m
uptime
}
# Function to troubleshoot network
network_check() {
echo "Checking network status..."
ping -c 4 google.com
netstat -tulnp
ip a | grep inet
}
# Function to monitor and restart a service
monitor_service() {
service_name="apache2"
if ! systemctl is-active --quiet $service_name; then
echo "$service_name is down. Restarting..."
sudo systemctl restart $service_name
fi
}
# Function to automate SSH login & remote command execution
remote_command() {
ssh user@remote-server "df -h"
}
# Run all functions
create_user
bulk_create_users
update_system
backup_system
cleanup_logs
system_health_check
network_check
monitor_service
remote_command
echo "All tasks completed successfully!"