When you are writing complex bash scripts to automate server deployments, timing is often critical. If your script restarts the central database service and then immediately attempts to write data to it on the very next line, the script will crash because the database needs a few seconds to fully boot up. To artificially pause your script and force the system to wait before executing the next line of code, you must use the sleep command.
How to Use the sleep Command
The sleep command is incredibly literal. It instructs the terminal shell to completely halt all processing for a specific mathematical duration. It requires zero configuration and zero administrative privileges.
By default, if you do not specify a unit of time, the command assumes you are asking for seconds.
If you want to pause your terminal (or your script) for exactly 10 seconds, type:
sleep 10
When you press Enter, the terminal prompt will vanish. The cursor will simply blink on an empty line for exactly ten seconds, doing absolutely nothing. Once the timer expires, the prompt will return, and the system is ready for the next command.
Using Advanced Time Units
While seconds are perfect for pausing scripts while a service restarts, you often need significantly longer delays. For example, if you want a script to trigger a massive system backup, but you want to delay the execution until midnight (2 hours from now) when the office is empty.
You can append specific single-letter suffixes to the command to change the unit of time:
- m (Minutes):
sleep 5mwill pause the system for 5 minutes. - h (Hours):
sleep 2hwill pause the system for 2 hours. - d (Days):
sleep 1dwill pause the system for an entire 24-hour day.
Combining Multiple Time Units
The sleep command is highly flexible and can accept multiple different time units simultaneously on the exact same line, allowing you to create hyper-specific countdown timers without having to calculate the total math yourself.
If you want a script to wait exactly 1 hour, 30 minutes, and 15 seconds before continuing, you do not need to calculate how many seconds that is. You simply run:
sleep 1h 30m 15s
The system will stack the values together and perfectly pause execution for the exact duration requested.