3 most common bash scripts
- Backup script: This script can be used to create backups of important files or directories. It can be configured to specify the source and destination directories, as well as the frequency of backups (e.g. daily, weekly, monthly).
Here is an example of a basic backup script:
#!/bin/bash
# Set the source and destination directories
SOURCE="/path/to/source/directory"
DESTINATION="/path/to/destination/directory"
# Set the filename for the backup
FILENAME="backup-$(date +%Y-%m-%d).tar.gz"
# Create the backup
tar -czf $DESTINATION/$FILENAME $SOURCE
# Print a message to confirm the backup was created
echo "Backup created at $DESTINATION/$FILENAME"
- Monitoring script: This script can be used to monitor a particular process or resource (e.g. CPU usage, disk space) and send an alert if it exceeds a certain threshold. This can be useful for detecting issues before they become major problems.
Here is an example of a basic monitoring script:
#!/bin/bash
# Set the threshold for the alert (in percent)
THRESHOLD=90
# Get the current CPU usage
USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
# Check if the usage is above the threshold
if [ "$USAGE" -gt "$THRESHOLD" ]; then
# Send the alert
echo "CPU usage is above threshold: $USAGE%" | mail -s "High CPU Usage Alert" admin@example.com
fi
- Automation script: This script can be used to automate a repetitive task or process. This can save time and reduce the risk of errors.
Here is an example of a basic automation script:
#!/bin/bash
# Set the source and destination directories
SOURCE="/path/to/source/directory"
DESTINATION="/path/to/destination/directory"
# Set the file extension to be processed
EXTENSION=".txt"
# Find all files with the specified extension in the source directory
FILES=$(find $SOURCE -name "*$EXTENSION")
# Process each file
for FILE in $FILES; do
# Perform some action on the file (e.g. convert to PDF)
# ...
# Move the processed file to the destination directory
mv $FILE $DESTINATION
done