Sometimes you will need to pause execution for a specific period within a shell script. To do that, you will need to use the
sleep command to delay for a specified amount of time in seconds, minutes, hours or days.
To pause using the
sleep command, pass the amount of time that has to paused as arguments to the command. This argument is a number indicating the number of seconds to sleep. The argument can include an optional suffix that may be ‘s’ for seconds (the default), ‘m’ for minutes, ‘h’ for hours or ‘d’ for days.
For example, to sleep for 30 seconds:
To sleep for 2 minutes:
To sleep for 1 hour:
To sleep for 1 day:
When do you use the sleep command
Let’s say that you will need to continuously monitor a process and that some actions have to be performed in the event that the process is no longer running. If you use a shell script to check on the process continuously in a
loop, there is a very high chance that the script will introduce a slight increase in the CPU load. If you include the
sleep command within the
loop the CPU increase will most probably be negligible.
#!/bin/bash process_name=some_process_name while true ; do ps -C $process_name [ $? -ne 0 ] && echo "warning: process not running" sleep 1m done
Sleep with millisecond precision
Normally, GNU versions of
sleep allow you to specify a floating number instead of just an integer for the sleep duration. So you can specify sleep durations of 2.5 seconds, 10.1 seconds, etc.