Interactive Script Techniques
Creating Dynamic and Responsive Scripts
Interactive bash scripts enhance user experience by providing dynamic input handling, validation, and responsive mechanisms.
#!/bin/bash
while true; do
clear
echo "===== System Utility Menu ====="
echo "1. Disk Usage"
echo "2. Network Status"
echo "3. System Information"
echo "4. Exit"
read -p "Enter your choice [1-4]: " choice
case $choice in
1) df -h ;;
2) netstat -tuln ;;
3) uname -a ;;
4) exit 0 ;;
*) echo "Invalid option. Press Enter to continue."; read ;;
esac
read -p "Press Enter to continue..."
done
graph TD
A[Display Menu] --> B{User Choice}
B --> |Valid| C[Execute Action]
B --> |Invalid| D[Show Error]
C --> E[Return to Menu]
D --> E
Comprehensive Validation
#!/bin/bash
validate_email() {
local email=$1
if [[ $email =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$ ]]; then
return 0
else
return 1
fi
}
while true; do
read -p "Enter your email: " email
if validate_email "$email"; then
echo "Valid email: $email"
break
else
echo "Invalid email format. Try again."
fi
done
Strategy |
Description |
Use Case |
Prompt & Validate |
Immediate validation |
User registration |
Multi-step Input |
Gradual information collection |
Complex forms |
Retry Mechanism |
Allow multiple input attempts |
Critical inputs |
Timeout and Default Values
#!/bin/bash
read -t 5 -p "Enter your name (timeout in 5 seconds): " name
if [ -z "$name" ]; then
name="Anonymous"
fi
echo "Hello, $name!"
5. User Experience Considerations
graph LR
A[Clear Prompts] --> B[Input Validation]
B --> C[Helpful Error Messages]
C --> D[User Guidance]
Best Practices
- Provide clear, concise instructions
- Implement robust input validation
- Offer meaningful error feedback
- Use timeouts for non-critical inputs
Conclusion
Interactive scripting transforms static scripts into dynamic, user-friendly tools. LabEx encourages continuous practice and experimentation with these techniques.