Read in 3 minutes

last updated 

How to Use the Linux Sleep Command to Pause a Bash Script

Sleep is a command line utility that allows you to suspends the calling process for a specified time. In other words, the sleep command pauses the execution on the next command for a given number of seconds.

The sleep command is especially useful when used within a bash shell script, for example when retrying a failed operation or inside a loop.

In this tutorial, we will show you how to use the Linux sleep command.

How to Use the sleep Command

The syntax for the sleep command is as follows:

sleep NUMBER [SUFFIX]...

The NUMBER may be a positive integer or a floating-point number.

The SUFFIX may be one of the following:

  • s - seconds (default)
  • m - minutes
  • h - hours
  • d - days

When no suffix is used it defaults to seconds.

When two or more arguments are specified the total amount of time is equivalent to the sum of their values.

Here are a few simple examples demonstrating how to use the sleep command:

  • Sleep for 5 seconds:

    sleep 5
  • Sleep for 0.5 seconds:

    sleep 0.5
  • Sleep for 2 minute and 30 seconds:

    sleep 2m 30s

Bash Script Examples

Below is the most basic example of how to use the sleep command in your Bash scripts. When you run the script it will print the current time in HH:MM:SS format. Then the sleep command will pause the script for 5 seconds. When the specified time period elapses the last line of the script will again print the current time.

#!/bin/bash

# start time
date +"%H:%M:%S"

# sleep for 5 seconds
sleep 5

# end time
date +"%H:%M:%S"

The output will look something like this:

13:34:40
13:34:45

Let’s take a look at a more advanced example.

#!/bin/bash

while :
do
  if ping -c 1 ip_address &> /dev/null
  then
    echo "Host is online"
    break
  fi
  sleep 5
done

The script above will check whether a host is online or not every 5 seconds and when the host goes online the script will notify you and stop.

How the script works:

  • In the first line, we are creating an infinite while loop.
  • Then we are using the ping command to determine whether the host with IP address of ip_address is reachable or not.
  • If the host is reachable the script will echo “Host is online” and terminate the loop.
  • If the host is not reachable the sleep command pauses the script for 5 seconds and then the loop starts from the beginning.

Conclusion

By now you should have a good understanding of how to use the Linux sleep command.

The sleep command is one of the simplest shell commands, accepting only one argument which is used to specify the sleep interval.