This skill should be used when the user asks to "create bash scripts", "automate Linux tasks", "monitor system resources", "backup files", "manage users", or "write production shell scripts". It provides ready-to-use shell script templates for system administration.
Add this skill
npx mdskills install sickn33/linux-shell-scriptingComprehensive bash script library with production-ready templates across 10 categories
1---2name: Linux Production Shell Scripts3description: This skill should be used when the user asks to "create bash scripts", "automate Linux tasks", "monitor system resources", "backup files", "manage users", or "write production shell scripts". It provides ready-to-use shell script templates for system administration.4metadata:5 author: zebbern6 version: "1.1"7---89# Linux Production Shell Scripts1011## Purpose1213Provide production-ready shell script templates for common Linux system administration tasks including backups, monitoring, user management, log analysis, and automation. These scripts serve as building blocks for security operations and penetration testing environments.1415## Prerequisites1617### Required Environment18- Linux/Unix system (bash shell)19- Appropriate permissions for tasks20- Required utilities installed (rsync, openssl, etc.)2122### Required Knowledge23- Basic bash scripting24- Linux file system structure25- System administration concepts2627## Outputs and Deliverables28291. **Backup Solutions** - Automated file and database backups302. **Monitoring Scripts** - Resource usage tracking313. **Automation Tools** - Scheduled task execution324. **Security Scripts** - Password management, encryption3334## Core Workflow3536### Phase 1: File Backup Scripts3738**Basic Directory Backup**39```bash40#!/bin/bash41backup_dir="/path/to/backup"42source_dir="/path/to/source"4344# Create a timestamped backup of the source directory45tar -czf "$backup_dir/backup_$(date +%Y%m%d_%H%M%S).tar.gz" "$source_dir"46echo "Backup completed: backup_$(date +%Y%m%d_%H%M%S).tar.gz"47```4849**Remote Server Backup**50```bash51#!/bin/bash52source_dir="/path/to/source"53remote_server="user@remoteserver:/path/to/backup"5455# Backup files/directories to a remote server using rsync56rsync -avz --progress "$source_dir" "$remote_server"57echo "Files backed up to remote server."58```5960**Backup Rotation Script**61```bash62#!/bin/bash63backup_dir="/path/to/backups"64max_backups=56566# Rotate backups by deleting the oldest if more than max_backups67while [ $(ls -1 "$backup_dir" | wc -l) -gt "$max_backups" ]; do68 oldest_backup=$(ls -1t "$backup_dir" | tail -n 1)69 rm -r "$backup_dir/$oldest_backup"70 echo "Removed old backup: $oldest_backup"71done72echo "Backup rotation completed."73```7475**Database Backup Script**76```bash77#!/bin/bash78database_name="your_database"79db_user="username"80db_pass="password"81output_file="database_backup_$(date +%Y%m%d).sql"8283# Perform database backup using mysqldump84mysqldump -u "$db_user" -p"$db_pass" "$database_name" > "$output_file"85gzip "$output_file"86echo "Database backup created: $output_file.gz"87```8889### Phase 2: System Monitoring Scripts9091**CPU Usage Monitor**92```bash93#!/bin/bash94threshold=909596# Monitor CPU usage and trigger alert if threshold exceeded97cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d. -f1)9899if [ "$cpu_usage" -gt "$threshold" ]; then100 echo "ALERT: High CPU usage detected: $cpu_usage%"101 # Add notification logic (email, slack, etc.)102 # mail -s "CPU Alert" admin@example.com <<< "CPU usage: $cpu_usage%"103fi104```105106**Disk Space Monitor**107```bash108#!/bin/bash109threshold=90110partition="/dev/sda1"111112# Monitor disk usage and trigger alert if threshold exceeded113disk_usage=$(df -h | grep "$partition" | awk '{print $5}' | cut -d% -f1)114115if [ "$disk_usage" -gt "$threshold" ]; then116 echo "ALERT: High disk usage detected: $disk_usage%"117 # Add alert/notification logic here118fi119```120121**CPU Usage Logger**122```bash123#!/bin/bash124output_file="cpu_usage_log.txt"125126# Log current CPU usage to a file with timestamp127timestamp=$(date '+%Y-%m-%d %H:%M:%S')128cpu_usage=$(top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d. -f1)129echo "$timestamp - CPU Usage: $cpu_usage%" >> "$output_file"130echo "CPU usage logged."131```132133**System Health Check**134```bash135#!/bin/bash136output_file="system_health_check.txt"137138# Perform system health check and save results to a file139{140 echo "System Health Check - $(date)"141 echo "================================"142 echo ""143 echo "Uptime:"144 uptime145 echo ""146 echo "Load Average:"147 cat /proc/loadavg148 echo ""149 echo "Memory Usage:"150 free -h151 echo ""152 echo "Disk Usage:"153 df -h154 echo ""155 echo "Top Processes:"156 ps aux --sort=-%cpu | head -10157} > "$output_file"158159echo "System health check saved to $output_file"160```161162### Phase 3: User Management Scripts163164**User Account Creation**165```bash166#!/bin/bash167username="newuser"168169# Check if user exists; if not, create new user170if id "$username" &>/dev/null; then171 echo "User $username already exists."172else173 useradd -m -s /bin/bash "$username"174 echo "User $username created."175176 # Set password interactively177 passwd "$username"178fi179```180181**Password Expiry Checker**182```bash183#!/bin/bash184output_file="password_expiry_report.txt"185186# Check password expiry for users with bash shell187echo "Password Expiry Report - $(date)" > "$output_file"188echo "=================================" >> "$output_file"189190IFS=$'\n'191for user in $(grep "/bin/bash" /etc/passwd | cut -d: -f1); do192 password_expires=$(chage -l "$user" 2>/dev/null | grep "Password expires" | awk -F: '{print $2}')193 echo "User: $user - Password Expires: $password_expires" >> "$output_file"194done195unset IFS196197echo "Password expiry report saved to $output_file"198```199200### Phase 4: Security Scripts201202**Password Generator**203```bash204#!/bin/bash205length=${1:-16}206207# Generate a random password208password=$(openssl rand -base64 48 | tr -dc 'a-zA-Z0-9!@#$%^&*' | head -c"$length")209echo "Generated password: $password"210```211212**File Encryption Script**213```bash214#!/bin/bash215file="$1"216action="${2:-encrypt}"217218if [ -z "$file" ]; then219 echo "Usage: $0 <file> [encrypt|decrypt]"220 exit 1221fi222223if [ "$action" == "encrypt" ]; then224 # Encrypt file using AES-256-CBC225 openssl enc -aes-256-cbc -salt -pbkdf2 -in "$file" -out "$file.enc"226 echo "File encrypted: $file.enc"227elif [ "$action" == "decrypt" ]; then228 # Decrypt file229 output_file="${file%.enc}"230 openssl enc -aes-256-cbc -d -pbkdf2 -in "$file" -out "$output_file"231 echo "File decrypted: $output_file"232fi233```234235### Phase 5: Log Analysis Scripts236237**Error Log Extractor**238```bash239#!/bin/bash240logfile="${1:-/var/log/syslog}"241output_file="error_log_$(date +%Y%m%d).txt"242243# Extract lines with "ERROR" from the log file244grep -i "error\|fail\|critical" "$logfile" > "$output_file"245echo "Error log created: $output_file"246echo "Total errors found: $(wc -l < "$output_file")"247```248249**Web Server Log Analyzer**250```bash251#!/bin/bash252log_file="${1:-/var/log/apache2/access.log}"253254echo "Web Server Log Analysis"255echo "========================"256echo ""257echo "Top 10 IP Addresses:"258awk '{print $1}' "$log_file" | sort | uniq -c | sort -rn | head -10259echo ""260echo "Top 10 Requested URLs:"261awk '{print $7}' "$log_file" | sort | uniq -c | sort -rn | head -10262echo ""263echo "HTTP Status Code Distribution:"264awk '{print $9}' "$log_file" | sort | uniq -c | sort -rn265```266267### Phase 6: Network Scripts268269**Network Connectivity Checker**270```bash271#!/bin/bash272hosts=("8.8.8.8" "1.1.1.1" "google.com")273274echo "Network Connectivity Check"275echo "=========================="276277for host in "${hosts[@]}"; do278 if ping -c 1 -W 2 "$host" &>/dev/null; then279 echo "[UP] $host is reachable"280 else281 echo "[DOWN] $host is unreachable"282 fi283done284```285286**Website Uptime Checker**287```bash288#!/bin/bash289websites=("https://google.com" "https://github.com")290log_file="uptime_log.txt"291292echo "Website Uptime Check - $(date)" >> "$log_file"293294for website in "${websites[@]}"; do295 if curl --output /dev/null --silent --head --fail --max-time 10 "$website"; then296 echo "[UP] $website is accessible" | tee -a "$log_file"297 else298 echo "[DOWN] $website is inaccessible" | tee -a "$log_file"299 fi300done301```302303**Network Interface Info**304```bash305#!/bin/bash306interface="${1:-eth0}"307308echo "Network Interface Information: $interface"309echo "========================================="310ip addr show "$interface" 2>/dev/null || ifconfig "$interface" 2>/dev/null311echo ""312echo "Routing Table:"313ip route | grep "$interface"314```315316### Phase 7: Automation Scripts317318**Automated Package Installation**319```bash320#!/bin/bash321packages=("vim" "htop" "curl" "wget" "git")322323echo "Installing packages..."324325for package in "${packages[@]}"; do326 if dpkg -l | grep -q "^ii $package"; then327 echo "[SKIP] $package is already installed"328 else329 sudo apt-get install -y "$package"330 echo "[INSTALLED] $package"331 fi332done333334echo "Package installation completed."335```336337**Task Scheduler (Cron Setup)**338```bash339#!/bin/bash340scheduled_task="/path/to/your_script.sh"341schedule_time="0 2 * * *" # Run at 2 AM daily342343# Add task to crontab344(crontab -l 2>/dev/null; echo "$schedule_time $scheduled_task") | crontab -345echo "Task scheduled: $schedule_time $scheduled_task"346```347348**Service Restart Script**349```bash350#!/bin/bash351service_name="${1:-apache2}"352353# Restart a specified service354if systemctl is-active --quiet "$service_name"; then355 echo "Restarting $service_name..."356 sudo systemctl restart "$service_name"357 echo "Service $service_name restarted."358else359 echo "Service $service_name is not running. Starting..."360 sudo systemctl start "$service_name"361 echo "Service $service_name started."362fi363```364365### Phase 8: File Operations366367**Directory Synchronization**368```bash369#!/bin/bash370source_dir="/path/to/source"371destination_dir="/path/to/destination"372373# Synchronize directories using rsync374rsync -avz --delete "$source_dir/" "$destination_dir/"375echo "Directories synchronized successfully."376```377378**Data Cleanup Script**379```bash380#!/bin/bash381directory="${1:-/tmp}"382days="${2:-7}"383384echo "Cleaning files older than $days days in $directory"385386# Remove files older than specified days387find "$directory" -type f -mtime +"$days" -exec rm -v {} \;388echo "Cleanup completed."389```390391**Folder Size Checker**392```bash393#!/bin/bash394folder_path="${1:-.}"395396echo "Folder Size Analysis: $folder_path"397echo "===================================="398399# Display sizes of subdirectories sorted by size400du -sh "$folder_path"/* 2>/dev/null | sort -rh | head -20401echo ""402echo "Total size:"403du -sh "$folder_path"404```405406### Phase 9: System Information407408**System Info Collector**409```bash410#!/bin/bash411output_file="system_info_$(hostname)_$(date +%Y%m%d).txt"412413{414 echo "System Information Report"415 echo "Generated: $(date)"416 echo "========================="417 echo ""418 echo "Hostname: $(hostname)"419 echo "OS: $(uname -a)"420 echo ""421 echo "CPU Info:"422 lscpu | grep -E "Model name|CPU\(s\)|Thread"423 echo ""424 echo "Memory:"425 free -h426 echo ""427 echo "Disk Space:"428 df -h429 echo ""430 echo "Network Interfaces:"431 ip -br addr432 echo ""433 echo "Logged In Users:"434 who435} > "$output_file"436437echo "System info saved to $output_file"438```439440### Phase 10: Git and Development441442**Git Repository Updater**443```bash444#!/bin/bash445git_repos=("/path/to/repo1" "/path/to/repo2")446447for repo in "${git_repos[@]}"; do448 if [ -d "$repo/.git" ]; then449 echo "Updating repository: $repo"450 cd "$repo"451 git fetch --all452 git pull origin "$(git branch --show-current)"453 echo "Updated: $repo"454 else455 echo "Not a git repository: $repo"456 fi457done458459echo "All repositories updated."460```461462**Remote Script Execution**463```bash464#!/bin/bash465remote_server="${1:-user@remote-server}"466remote_script="${2:-/path/to/remote/script.sh}"467468# Execute a script on a remote server via SSH469ssh "$remote_server" "bash -s" < "$remote_script"470echo "Remote script executed on $remote_server"471```472473## Quick Reference474475### Common Script Patterns476477| Pattern | Purpose |478|---------|---------|479| `#!/bin/bash` | Shebang for bash |480| `$(date +%Y%m%d)` | Date formatting |481| `$((expression))` | Arithmetic |482| `${var:-default}` | Default value |483| `"$@"` | All arguments |484485### Useful Commands486487| Command | Purpose |488|---------|---------|489| `chmod +x script.sh` | Make executable |490| `./script.sh` | Run script |491| `nohup ./script.sh &` | Run in background |492| `crontab -e` | Edit cron jobs |493| `source script.sh` | Run in current shell |494495### Cron Format496Minute(0-59) Hour(0-23) Day(1-31) Month(1-12) Weekday(0-7, 0/7=Sun)497498## Constraints and Limitations499500- Always test scripts in non-production first501- Use absolute paths to avoid errors502- Quote variables to handle spaces properly503- Many scripts require root/sudo privileges504- Use `bash -x script.sh` for debugging505
Full transparency — inspect the skill content before installing.