Linux Production Shell Scripts
Certainly! Here’s a Medium blog format featuring 30 essential Linux production shell scripts. These scripts cater to various needs, from system monitoring to file management. Each section provides a brief explanation followed by the script itself.
30 Essential Linux Production Shell Scripts
Linux shell scripting is an invaluable skill for system administrators and developers alike. Here are 30 production-ready scripts that can help streamline your workflow and manage system resources efficiently.
1. File Backup Script
Create a timestamped backup of a source directory.
#!/bin/bash
backup_dir="/path/to/backup"
source_dir="/path/to/source"
tar -czf "$backup_dir/backup_$(date +%Y%m%d_%H%M%S).tar.gz" "$source_dir"
echo "Backup created successfully."
2. Syste Monitoring Script
Monitor CPU usage and alert if it exceeds a certain threshold.
#!/bin/bash
threshold=90
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d. -f1)
if [ "$cpu_usage" -gt "$threshold" ]; then
echo "High CPU usage detected: $cpu_usage%"
fi
3. User Account Management Script
Check if a user exists, and if not, create a new one.
#!/bin/bash
username="newuser"
if id "$username" &>/dev/null; then
echo "User $username already exists."
else
useradd -m "$username"
echo "User $username created."
fi
4. Log Analyzer Script
Extract lines with “ERROR” from a log file.
#!/bin/bash
logfile="/path/to/logfile.log"
grep "ERROR" "$logfile" > error_log.txt
echo "Error log created."
5. Password Generator Script
Generate a random password.
#!/bin/bash
length=12
password=$(openssl rand -base64 $length)
echo "Generated password: $password"
6. File Encryption Script
Encrypt a file using AES-256-CBC.
#!/bin/bash
file="/path/to/file.txt"
openssl enc -aes-256-cbc -salt -in "$file" -out "$file.enc"
echo "File encrypted: $file.enc"
7. Automated Software Installation Script
Install a list of packages using apt-get
.
#!/bin/bash
packages=("package1" "package2" "package3")
for package in "${packages[@]}"; do
sudo apt-get install "$package" -y
done
echo "Packages installed successfully."
8. Network Connectivity Checker Script
Check network connectivity by pinging a host.
#!/bin/bash
host="example.com"
if ping -c 1 "$host" &>/dev/null; then
echo "Network is up."
else
echo "Network is down."
fi
9. Website Uptime Checker Script
Check if a website is accessible.
#!/bin/bash
website="https://example.com"
if curl --output /dev/null --silent --head --fail "$website"; then
echo "Website is up."
else
echo "Website is down."
fi
10. Data Cleanup Script
Remove files older than 7 days in a specified directory.
#!/bin/bash
directory="/path/to/cleanup"
find "$directory" -type f -mtime +7 -exec rm {} \;
echo "Old files removed."
11. CPU Usage Tracker Script
Log current CPU usage to a file with a timestamp.
#!/bin/bash
output_file="cpu_usage_log.txt"
echo "$(date) $(top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d. -f1)%" >> "$output_file"
echo "CPU usage logged."
12. System Information Script
Gather and save system information to a file.
#!/bin/bash
output_file="system_info.txt"
echo "System Information:" > "$output_file"
echo "-------------------" >> "$output_file"
echo "Hostname: $(hostname)" >> "$output_file"
echo "OS: $(uname -a)" >> "$output_file"
echo "Memory: $(free -h)" >> "$output_file"
echo "Disk Space: $(df -h)" >> "$output_file"
echo "System info saved to $output_file."
13. Task Scheduler Script
Schedule a task using cron.
#!/bin/bash
scheduled_task="/path/to/your_script.sh"
schedule_time="0 2 * * *"
echo "$schedule_time $scheduled_task" | crontab -
echo "Task scheduled successfully."
14. Disk Space Monitoring Script
Monitor disk usage and trigger alert if the threshold is exceeded.
#!/bin/bash
threshold=90
disk_usage=$(df -h | grep "/dev/sda1" | awk '{print $5}' | cut -d% -f1)
if [ "$disk_usage" -gt "$threshold" ]; then
echo "High disk usage detected: $disk_usage%"
fi
15. Remote Server Backup Script
Backup files/directories to a remote server using rsync.
#!/bin/bash
source_dir="/path/to/source"
remote_server="user@remoteserver:/path/to/backup"
rsync -avz "$source_dir" "$remote_server"
echo "Files backed up to remote server."
16. Environment Setup Script
Customize your environment setup.
#!/bin/bash
echo "Setting up development environment..."
echo "Development environment set up successfully."
17. File Compression Script
Compress a file using gzip.
#!/bin/bash
file_to_compress="/path/to/file.txt"
gzip "$file_to_compress"
echo "File compressed: $file_to_compress.gz"
18. Database Backup Script
Perform a database backup using mysqldump.
#!/bin/bash
database_name="your_database"
output_file="database_backup_$(date +%Y%m%d).sql"
mysqldump -u username -ppassword "$database_name" > "$output_file"
echo "Database backup created: $output_file"
19. Git Repository Updater Script
Update a Git repository.
#!/bin/bash
git_repo="/path/to/your/repo"
cd "$git_repo"
git pull origin master
echo "Git repository updated."
20. Directory Synchronization Script
Synchronize directories using rsync.
#!/bin/bash
source_dir="/path/to/source"
destination_dir="/path/to/destination"
rsync -avz "$source_dir" "$destination_dir"
echo "Directories synchronized successfully."
21. Web Server Log Analyzer Script
Analyze a web server log to count unique IP addresses.
#!/bin/bash
log_file="/var/log/apache2/access.log"
awk '{print $1}' "$log_file" | sort | uniq -c | sort -nr
echo "Web server log analyzed."
22. System Health Check Script
Perform a system health check and save results to a file.
#!/bin/bash
output_file="system_health_check.txt"
echo "System Health Check:" > "$output_file"
echo "---------------------" >> "$output_file"
echo "Uptime: $(uptime)" >> "$output_file"
echo "Load Average: $(cat /proc/loadavg)" >> "$output_file"
echo "Memory Usage: $(free -m)" >> "$output_file"
echo "System health check results saved to $output_file."
23. Automated Database Cleanup Script
Clean up old database backups older than specified days.
#!/bin/bash
database_name="your_database"
days_to_keep=7
find /path/to/database/backups -name "$database_name*.sql" -mtime +"$days_to_keep" -exec rm {} \;
echo "Old database backups cleaned up."
24. User Password Expiry Checker Script
Check password expiry for users with a bash shell.
#!/bin/bash
IFS=$'\n'
for user in $(cat /etc/passwd | grep "/bin/bash" | cut -d: -f1); do
password_expires=$(chage -l "$user" | grep "Password expires" | awk '{print $4}')
echo "User: $user, Password Expires: $password_expires"
done
unset IFS
25. Service Restart Script
Restart a specified service.
#!/bin/bash
service_name="your_service"
sudo systemctl restart "$service_name"
echo "Service $service_name restarted."
26. Folder Size Checker Script
Check and display the size of a specified folder.
#!/bin/bash
folder_path="/path/to/folder"
du -sh "$folder_path"
echo "Folder size checked."
27. Backup Rotation Script
Manage backup rotation effectively.
#!/bin/bash
backup_dir="/path/to/backups"
# Logic for backup rotation here
echo "Backup rotation processed."
28. Automated System Update Script
Keep your system packages up to date.
#!/bin/bash
sudo apt-get update && sudo apt-get upgrade -y
echo "System updated successfully."
29. App Log Cleanup Script
Remove application logs older than a specified number of days.
#!/bin/bash
log_directory="/path/to/logs"
find "$log_directory" -type f -mtime +30 -exec rm {} \;
echo "Old application logs cleaned up."
30. System Load Average Notification Script
Notify if the system load average exceeds a threshold.
#!/bin/bash
load_average=$(uptime | awk '{print $10}' | sed 's/,//')
threshold=1.0
if (( $(echo "$load_average > $threshold" | bc -l) )); then
echo "Alert! Load average too high: $load_average"
fi
These scripts offer a solid foundation for managing various tasks in a Linux environment. Tailor them to your needs, and you’ll find your day-to-day operations much more efficient! Happy scripting! 🌟
For more resources on Linux scripting, consider checking out Linux Shell Scripting Tutorial.