In Linux, the sleep command is used to delay scripts for a specified time. It can also be used in the terminal to execute commands at a certain pace.
Table of contents.
The sleep command delays execution of shell scripts and commands for a specified. This could be minutes, seconds, hours, or even days. In this article, we learn about this command through various examples.
We usually write sleep commands in the following format:
$ sleep NUMBER[SUFFIX]... # OR $ sleep OPTION
In the command, we specify a number, this is the number of seconds, minutes, hours, or days we want the command or script to sleep for.
The suffix can be;
s: for seconds.
m: for minutes.
h: for hours.
d: for days.
By default the time used with sleep is in seconds, we can also specify minutes, seconds, hours, or even microseconds.
For example, to send ICMP packets every 5 seconds using the sleep command we write:
$ while true; do ping -c 2 188.8.131.52; sleep 5; done
In this example after every 5 seconds, 2 pings are sent to the host 184.108.40.206.
We can also use it in a script as follows:
#!/bin/bash x=10 while [ $x -gt 5 ]; do time=$(date +"%T") echo "#$x $time" sleep 2 x=$(($x - 1)) done
Here, we print the value of a variable x after every two seconds until its value is less than or equal to 5.
Apart from specifying time in seconds, we can also specify it in minutes. For example, to print out the currently logged in users using the w command after every minute, we write:
$ while true; do w; sleep 1m; done
To exit the sleep command we press CTRL + C, which takes us out of the sleep mode.
We can also make execution pause for a fraction of a second, for example:
$ while true; do w; sleep .5s; done
The free command displays information about memory usage, combined with the sleep command, we can print out memory details after a minute by writing:
$ sleep 1m && free
To print this information in a fraction of a second, say 1/10th of a second, we write:
$ sleep .1 && free
This command works by stopping the currently executing process, it keeps resources on hold until the specified time runs out then starts execution again.
We also have the wait command, unlike the sleep command, which waits for background processes to complete then returns the exit status.
As we saw, the sleep command pauses the terminal and this is not preferable in some cases. Assuming we want to pause execution for days, a better Linux utility to use would be crontab.
For a comprehensive guide for the sleep command, we can read its manual by executing the command $ man sleep.