The sleep command is very useful in many shell scripts. It is used when you want to wait for some time to complete the specific operation before starting the next operation in the shell script. In simple terms, it is used to delay of execution of the next command. You can set a fixed amount of time by seconds, minutes, hours, and days.

In this post, we will show you how to use sleep command with practical examples.

Basic Syntax of Sleep Command

The basic syntax of the sleep command is shown below:

sleep NUMBER[SUFFIX]...

Sleep supports multiple values to calculate the duration of sleep:

  • s – seconds
  • m – minutes
  • h – hours
  • d – days

To check the version of the sleep command, use the following command:

sleep --version

You should see the following output:

sleep (GNU coreutils) 8.21
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Jim Meyering and Paul Eggert.

Sleep Command Examples

By default, the sleep command will take time in seconds.

For example, run the following command:

sleep 7

This will pause the terminal for 7 seconds.

You can use the m option to specify the time in a minute:

sleep 2m

This will pause the terminal for 2 minutes.

Press CTRL + C to exit from the sleep mode.

Let’s take another example, run the date and cal command with sleep command. The date command will print the current date and the cal command will print the calendar after waiting for 5 seconds.

date && sleep 1 && echo "One" && sleep 1 && echo "Two" && sleep 1 && echo "Three" && sleep 1 && echo "Four" && sleep 1 && echo "Five" && cal

You should see the following output:

Sun Jun 27 20:44:12 IST 2021
One
Two
Three
Four
Five
     June 2021        
Su Mo Tu We Th Fr Sa  
       1  2  3  4  5  
 6  7  8  9 10 11 12  
13 14 15 16 17 18 19  
20 21 22 23 24 25 26  
27 28 29 30           

Let’s take another example that pauses a shell script for 5 seconds.

First, create a shell script with the following command:

nano bash.sh

Add the following lines:

#!/bin/bash

SLEEP_TIME="5"
echo "Current time: $(date +%T)"
echo "Hi, Wait for ${SLEEP_TIME} seconds ..."
sleep ${SLEEP_TIME}
echo "All done and current time: $(date +%T)"

Save the file, then run it with the following command:

bash bash.sh

You should see the following output:

Current time: 20:52:04
Hi, Wait for 5 seconds ...
All done and current time: 20:52:09

Conclusion

That’s it. You have now enough knowledge of how to use the sleep command in Linux. Try using it on your dedicated server from Atlantic.Net, and for more information, visit the sleep command manual page.