In Bash scripting, the sleep
command is used to pause the execution of a script for a specified duration. This is useful for creating delays, scheduling tasks, and managing timing in scripts.
The basic syntax for the sleep
command is:
sleep duration
The duration can be specified in seconds, minutes, hours, or days by appending s
, m
, h
, or d
to the number.
Let's look at some examples of how to use the sleep
command in Bash:
This command pauses the script for 5 seconds.
#!/bin/bash
# Sleep for 5 seconds
sleep 5
echo "5 seconds have passed"
In this example, the script pauses for 5 seconds before printing the message.
This command pauses the script for 2 minutes.
#!/bin/bash
# Sleep for 2 minutes
sleep 2m
echo "2 minutes have passed"
In this example, the script pauses for 2 minutes before printing the message.
This command pauses the script for 1 hour.
#!/bin/bash
# Sleep for 1 hour
sleep 1h
echo "1 hour has passed"
In this example, the script pauses for 1 hour before printing the message.
This command pauses the script for 1 day.
#!/bin/bash
# Sleep for 1 day
sleep 1d
echo "1 day has passed"
In this example, the script pauses for 1 day before printing the message.
This command pauses the script for a mixed duration of 1 minute and 30 seconds.
#!/bin/bash
# Sleep for 1 minute and 30 seconds
sleep 1m 30s
echo "1 minute and 30 seconds have passed"
In this example, the script pauses for 1 minute and 30 seconds before printing the message.
The sleep
command can be used in scripts to create delays between commands, simulate processing time, or schedule repeated tasks.
#!/bin/bash
# Print message
echo "Starting process..."
# Sleep for 3 seconds
sleep 3
# Print message
echo "Process completed after 3 seconds"
In this example, the script prints a message, pauses for 3 seconds, and then prints another message.
Using the sleep
command in Bash is essential for pausing script execution for a specified duration. It is useful for creating delays, scheduling tasks, and managing timing in shell scripts. Understanding how to use the sleep
command with different durations can help you write more effective and controlled Bash scripts.