- Posted on
- • System Administration
Automating Sysadmin Tasks with Bash Scripting: A Practical Guide
- Author
-
-
- User
- Khalequzzaman
- Posts by this author
- Posts by this author
-
As a sysadmin, repetitive tasks can consume a significant amount of your time. Fortunately, Bash scripting allows you to automate these tasks, saving time and reducing the risk of human error. In this post, we’ll explore the basics of Bash scripting and walk through practical examples to help you automate common sysadmin tasks.
What is Bash Scripting?
Bash (Bourne Again Shell) is a command-line interpreter for Linux and Unix-based systems. Bash scripting involves writing a series of commands in a file (a script) that can be executed to perform tasks automatically.
Getting Started with Bash Scripting
1. Creating a Bash Script
To create a Bash script, follow these steps:
- Open a text editor (e.g.,
nanoorvim). - Start the script with a shebang (
#!) to specify the interpreter:
bash #!/bin/bash - Add your commands.
- Save the file with a
.shextension (e.g.,myscript.sh).
2. Making the Script Executable
Before running the script, make it executable:
chmod +x myscript.sh
3. Running the Script
Execute the script using:
./myscript.sh
Practical Bash Scripting Examples
Example 1: Backup a Directory
Automate the backup of a directory using tar.
#!/bin/bash
# Define source and backup locations
SOURCE_DIR="/home/user/documents"
BACKUP_DIR="/backup"
BACKUP_FILE="backup_$(date +%Y%m%d).tar.gz"
# Create the backup
tar -czvf $BACKUP_DIR/$BACKUP_FILE $SOURCE_DIR
# Check if the backup was successful
if [ $? -eq 0 ]; then
echo "Backup completed successfully: $BACKUP_FILE"
else
echo "Backup failed!"
fi
Example 2: Monitor Disk Usage
Send an alert if disk usage exceeds a threshold.
#!/bin/bash
# Set the threshold (e.g., 90%)
THRESHOLD=90
# Get current disk usage
USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
# Check if usage exceeds the threshold
if [ $USAGE -gt $THRESHOLD ]; then
echo "Disk usage is above $THRESHOLD%: $USAGE%" | mail -s "Disk Usage Alert" admin@example.com
fi
Example 3: Automate User Creation
Create multiple users from a list.
#!/bin/bash
# Path to the user list file
USER_LIST="/path/to/userlist.txt"
# Read the file line by line
while read USER; do
# Create the user
useradd $USER
echo "User $USER created."
done < $USER_LIST
The userlist.txt file should contain one username per line:
user1
user2
user3
Example 4: Check System Health
Monitor CPU, memory, and disk usage.
#!/bin/bash
# Get CPU usage
CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
# Get memory usage
MEMORY=$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2 }')
# Get disk usage
DISK=$(df -h / | awk 'NR==2{print $5}')
# Display the results
echo "CPU Usage: $CPU%"
echo "Memory Usage: $MEMORY"
echo "Disk Usage: $DISK"
Example 5: Automate Log Cleanup
Delete log files older than 30 days.
#!/bin/bash
# Define the log directory
LOG_DIR="/var/log"
# Find and delete logs older than 30 days
find $LOG_DIR -type f -name "*.log" -mtime +30 -exec rm -f {} \;
echo "Old logs cleaned up."
Tips for Writing Effective Bash Scripts
- Add Comments: Use
#to add comments and explain your code. - Use Variables: Store reusable values in variables to make your script more flexible.
- Error Handling: Use
ifstatements to check for errors and handle them gracefully. - Test Incrementally: Test your script step by step to ensure it works as expected.
- Use Cron Jobs: Schedule your scripts to run automatically using
cron.
Example of a cron job to run a script daily at 2 AM:
0 2 * * * /path/to/myscript.sh
Conclusion
Bash scripting is a powerful tool for automating sysadmin tasks, saving time, and improving efficiency. By mastering the basics and applying them to real-world scenarios, you can streamline your workflow and focus on more critical tasks.