Practical Script Examples
Scenario-Based File Existence Scripts
1. Configuration File Validation
#!/bin/bash
CONFIG_FILE="/etc/myapp/config.conf"
if [ ! -f "$CONFIG_FILE" ]; then
echo "Error: Configuration file not found!"
echo "Creating default configuration..."
mkdir -p /etc/myapp
touch "$CONFIG_FILE"
fi
2. Backup Script with Existence Check
#!/bin/bash
SOURCE_DIR="/home/labex/documents"
BACKUP_DIR="/backup/documents"
## Ensure source and backup directories exist
if [ ! -d "$SOURCE_DIR" ]; then
echo "Source directory does not exist!"
exit 1
fi
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p "$BACKUP_DIR"
echo "Created backup directory"
fi
## Perform backup
cp -r "$SOURCE_DIR"/* "$BACKUP_DIR"
Advanced File Handling Scenarios
3. Log Rotation Script
#!/bin/bash
LOG_FILE="/var/log/myapp.log"
MAX_SIZE=$((10 * 1024 * 1024)) ## 10MB
if [ -f "$LOG_FILE" ]; then
FILE_SIZE=$(stat -c%s "$LOG_FILE")
if [ "$FILE_SIZE" -gt "$MAX_SIZE" ]; then
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
mv "$LOG_FILE" "$LOG_FILE.$TIMESTAMP"
touch "$LOG_FILE"
echo "Log file rotated"
fi
fi
Error Handling Workflow
graph TD
A[Start Script] --> B{Check File Exists}
B -->|Yes| C[Perform Operation]
B -->|No| D[Create File/Handle Error]
C --> E[Validate File Permissions]
E -->|Readable| F[Process File]
E -->|Not Readable| G[Report Error]
Common Use Cases
Scenario |
Test Operator |
Purpose |
Check Configuration |
-f |
Validate config file |
Verify Executable |
-x |
Check script permissions |
Directory Validation |
-d |
Ensure directory exists |
Readable File Check |
-r |
Confirm file accessibility |
4. Interactive Script with Multiple Checks
#!/bin/bash
SCRIPT_DIR="/home/labex/scripts"
DEPLOY_SCRIPT="$SCRIPT_DIR/deploy.sh"
## Comprehensive file existence and permission check
if [[ -d "$SCRIPT_DIR" && -f "$DEPLOY_SCRIPT" && -x "$DEPLOY_SCRIPT" ]]; then
echo "Deployment script is ready"
"$DEPLOY_SCRIPT"
else
echo "Deployment setup incomplete"
echo "Checking: "
[ -d "$SCRIPT_DIR" ] || echo "- Script directory missing"
[ -f "$DEPLOY_SCRIPT" ] || echo "- Deployment script not found"
[ -x "$DEPLOY_SCRIPT" ] || echo "- Deployment script not executable"
fi
Key Takeaways
- Always validate file existence before operations
- Use appropriate test operators
- Implement robust error handling
- Create fallback mechanisms
By practicing these examples on LabEx, you'll develop more reliable and efficient shell scripts.