How to Use the sleep Command to Delay the Execution of a Script in Linux

When writing bash scripts in Linux, you often need to pause the execution of your code. For example, if your script starts a background server and then attempts to connect to it, you need to wait a few seconds to ensure the server has fully initialized before making the connection. To introduce a deliberate pause or delay into your scripts, you can use the sleep command.

How the sleep Command Works

The sleep command simply suspends the calling process for a specified amount of time. It takes a single number as its argument, which represents the duration of the delay.

By default, if you do not specify a unit of time, the sleep command assumes you mean seconds. To pause a script for exactly five seconds, you would write:

sleep 5

Using Different Units of Time

If you need to pause a script for a longer duration, calculating the exact number of seconds can be annoying (e.g., sleep 7200 for two hours). Fortunately, the sleep command accepts specific suffix letters to define different time units:

  • s: Seconds (the default, e.g., sleep 10s)
  • m: Minutes (e.g., sleep 5m pauses for five minutes)
  • h: Hours (e.g., sleep 2h pauses for two hours)
  • d: Days (e.g., sleep 1d pauses for a full 24 hours)

Combining Multiple Time Units

You can also combine these suffixes to create highly specific, readable delays without doing any math. The sleep command will simply add all the values together.

For example, if you want a script to pause for exactly 1 hour, 30 minutes, and 15 seconds, you would write:

sleep 1h 30m 15s

When the script hits that line, the terminal will hang silently for exactly that duration before moving on to execute the very next line of code.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.