In this short guide, we will learn how to pause a shell script for a specified time before continuing execution. Adding delays is essential for timing operations, waiting for services, rate limiting API calls, and controlling script flow in automation tasks.
Here you can find the short answer:
(1) Pause for 1 second
sleep 1
(2) Pause for 5 seconds
sleep 5
(3) Pause for milliseconds (0.5 seconds)
sleep 0.5
So let's see how to add delays and pauses to Bash scripts effectively.
Problem: Controlling Script Execution Timing
Shell scripts often need to pause execution for:
- Waiting for services to start (databases, web servers)
- Rate limiting API requests to avoid throttling
- Displaying messages long enough to be read
- Synchronizing operations between different processes
- Avoiding system overload in loops
Solution: Use the sleep command with various time units.
1: Basic Sleep Command (Seconds)
The sleep command pauses script execution for a specified number of seconds:
#!/bin/bash
echo "Starting backup process..."
sleep 3
echo "Backup started after 3 seconds"
sleep 2
echo "Backup completed after 5 seconds total"
Output Result:
Starting backup process...
(waits 3 seconds)
Backup started after 3 seconds
(waits 2 seconds)
Backup completed after 5 seconds total
How it works:
sleep 3- Pauses for 3 secondssleep 2- Pauses for 2 seconds- Script execution resumes after each delay
- Total delay is cumulative (5 seconds)
Real-world example: Waiting for database server to fully initialize before running migration scripts in deployment automation.
2: Sleep with Fractional Seconds
Use decimal values for sub-second delays (milliseconds):
#!/bin/bash
echo "Processing API requests with rate limiting..."
for i in {1..5}; do
echo "Request $i to api.example.com"
curl -s "https://api.example.com/data?id=$i" > /dev/null
sleep 0.5
done
echo "All requests completed"
Output Result:
Processing API requests with rate limiting...
Request 1 to api.example.com
(waits 0.5 seconds)
Request 2 to api.example.com
(waits 0.5 seconds)
Request 3 to api.example.com
(waits 0.5 seconds)
Request 4 to api.example.com
(waits 0.5 seconds)
Request 5 to api.example.com
(waits 0.5 seconds)
All requests completed
Use case: Rate limiting API calls to stay within provider limits (e.g., 2 requests per second = 0.5 second delay).
3: Sleep with Different Time Units
Specify delays using minutes, hours, or days with suffix notation:
#!/bin/bash
echo "Starting server health check..."
echo "Timestamp: $(date)"
echo "Waiting 30 seconds before first check..."
sleep 30s
echo "First check at: $(date)"
echo "Waiting 2 minutes before next check..."
sleep 2m
echo "Second check at: $(date)"
echo "Monitoring complete"
Output Result:
Starting server health check...
Timestamp: Mon Dec 16 10:00:00 UTC 2024
Waiting 30 seconds before first check...
(waits 30 seconds)
First check at: Mon Dec 16 10:00:30 UTC 2024
Waiting 2 minutes before next check...
(waits 2 minutes)
Second check at: Mon Dec 16 10:02:30 UTC 2024
Monitoring complete
Time unit suffixes:
s- Seconds (default, can be omitted)m- Minutesh- Hoursd- Days
Examples:
sleep 30s # 30 seconds
sleep 5m # 5 minutes
sleep 2h # 2 hours
sleep 1d # 1 day
4: Dynamic Sleep Duration
Calculate sleep duration dynamically based on variables or conditions:
#!/bin/bash
retry_count=0
max_retries=3
delay=1
while [ $retry_count -lt $max_retries ]; do
echo "Attempt $((retry_count + 1)) - Connecting to database..."
if ping -c 1 db.example.com &> /dev/null; then
echo "Database is online!"
break
else
echo "Database offline. Retrying in $delay seconds..."
sleep $delay
retry_count=$((retry_count + 1))
delay=$((delay * 2))
fi
done
Output Result:
Attempt 1 - Connecting to database...
Database offline. Retrying in 1 seconds...
(waits 1 second)
Attempt 2 - Connecting to database...
Database offline. Retrying in 2 seconds...
(waits 2 seconds)
Attempt 3 - Connecting to database...
Database is online!
Features:
- Exponential backoff - Delay doubles each retry (1s, 2s, 4s...)
- Dynamic calculation - Sleep time stored in variable
- Retry logic - Common pattern for service health checks
Use case: Waiting for microservices to start in Docker Compose or Kubernetes deployments with increasing retry intervals.
5: Progress Indicator During Sleep
Display a countdown or progress indicator while sleeping:
#!/bin/bash
echo "Deploying application to production..."
duration=10
for i in $(seq $duration -1 1); do
echo -ne "Starting in $i seconds...\r"
sleep 1
done
echo "Deployment started! "
Output Result:
Deploying application to production...
Starting in 10 seconds...
Starting in 9 seconds...
Starting in 8 seconds...
...
Starting in 1 seconds...
Deployment started!
How it works:
echo -ne- No newline, enables overwriting\r- Carriage return, moves cursor to line start- Creates countdown effect
Common Use Cases
Service Startup: Wait for databases, web servers, message queues to initialize
Rate Limiting: Control API request frequency to avoid throttling
Retry Logic: Implement exponential backoff for failed operations
User Experience: Display messages long enough to be read in interactive scripts
Testing: Add delays between test steps for debugging
Monitoring: Schedule periodic health checks in cron jobs
Deployment: Coordinate multi-stage deployments with timed pauses
Alternative: Timeout Command
For maximum wait time with early exit:
timeout 30s command_that_might_hang
Runs command but kills it after 30 seconds if not completed.
Quick Reference Table
| Command | Duration | Use Case |
|---|---|---|
sleep 1 |
1 second | Quick delays |
sleep 0.5 |
500 milliseconds | Rate limiting |
sleep 30s |
30 seconds | Service startup |
sleep 5m |
5 minutes | Batch processing |
sleep 2h |
2 hours | Long-running tasks |
sleep 1d |
1 day | Scheduled maintenance |