sleep
Overview
The sleep
command pauses execution for a specified amount of time. It’s essential for creating delays in scripts, timing operations, and controlling execution flow.
Syntax
sleep number[suffix]
Time Suffixes
Suffix | Unit |
---|---|
s |
Seconds (default) |
m |
Minutes |
h |
Hours |
d |
Days |
Key Use Cases
- Script timing and delays
- Rate limiting operations
- Polling intervals
- System testing
- Batch processing control
Examples with Explanations
Example 1: Basic Sleep
sleep 5
Pauses for 5 seconds
Example 2: Different Time Units
sleep 2m # 2 minutes
sleep 1h # 1 hour
sleep 0.5 # Half second
Example 3: In Script Context
echo "Starting process..."
sleep 3
echo "Process started!"
Common Usage Patterns
Retry with delay:
while ! ping -c 1 google.com; do echo "Waiting for network..." sleep 5 done
Batch processing:
for file in *.txt; do process_file "$file" sleep 1 # Avoid overwhelming system done
Monitoring loops:
while true; do check_system_status sleep 30 done
Fractional Seconds
Decimal notation:
sleep 0.5 # Half second sleep 1.5 # 1.5 seconds sleep 0.1 # 100 milliseconds
Very short delays:
sleep 0.01 # 10 milliseconds
Performance Analysis
- Minimal CPU usage during sleep
- No active polling
- Efficient for timing control
- Good for rate limiting
- System scheduler dependent
Best Practices
- Use appropriate time units
- Consider system load
- Handle interrupts gracefully
- Use for rate limiting
- Avoid unnecessary delays
Scripting Applications
Service startup delay:
#!/bin/bash echo "Starting services..." start_database sleep 10 # Wait for database to initialize start_application
Retry mechanism:
retry_command() { local max_attempts=5 local delay=2 for i in $(seq 1 $max_attempts); do if command; then return 0 fi echo "Attempt $i failed, retrying in ${delay}s..." sleep $delay delay=$((delay * 2)) # Exponential backoff done return 1 }
Rate Limiting
API calls:
for endpoint in "${endpoints[@]}"; do curl "$endpoint" sleep 1 # Respect rate limits done
File processing:
find . -name "*.log" | while read file; do process_log "$file" sleep 0.5 # Prevent I/O overload done
System Testing
Load testing:
for i in {1..100}; do make_request & sleep 0.1 # Gradual load increase done
Stress testing:
while true; do stress_test_component sleep 60 # Cool-down period done
Integration Examples
With monitoring:
while true; do if ! check_service_health; then alert_admin sleep 300 # Wait before next check else sleep 60 # Normal check interval fi done
Deployment script:
deploy_application echo "Waiting for application to start..." sleep 30 run_health_checks
Signal Handling
Sleep can be interrupted by signals:
# This will be interrupted by Ctrl+C
sleep 3600 &
PID=$!
# Later: kill $PID
Precision Considerations
System scheduler affects precision
Minimum sleep time varies by system
High-precision alternatives:
# For microsecond precision usleep 500000 # 0.5 seconds # For nanosecond precision (if available) nanosleep 0.000000001 # 1 nanosecond
Error Handling
Invalid time format:
if ! sleep "$delay" 2>/dev/null; then echo "Invalid delay: $delay" exit 1 fi
Interrupted sleep:
sleep 60 || echo "Sleep was interrupted"
Alternatives and Workarounds
Using read with timeout:
read -t 5 -p "Press enter to continue (5s timeout): "
Using timeout command:
timeout 5 cat # Waits up to 5 seconds for input
Real-world Examples
Database backup script:
#!/bin/bash echo "Starting backup..." mysqldump database > backup.sql echo "Backup complete, waiting before compression..." sleep 5 gzip backup.sql echo "Backup compressed and ready"
Service health monitor:
while true; do if curl -f http://localhost:8080/health; then echo "Service healthy" sleep 60 else echo "Service unhealthy, checking again soon" sleep 10 fi done
Troubleshooting
- Sleep not working as expected
- Precision issues
- Signal interruption
- Invalid time formats
- System clock changes
Security Considerations
Avoid predictable delays in security contexts
Consider timing attacks
Use random delays when appropriate:
# Random delay between 1-5 seconds sleep $((1 + RANDOM % 5))
Performance Impact
No CPU usage during sleep
Process remains in memory
Can affect script execution time
Consider parallel execution:
# Instead of sequential delays for i in {1..10}; do (process_item $i; sleep 1) & done wait # Wait for all background jobs