How to use bash sleep command in Linux?

73
linux

When you will execute a script with multiple command sequence in Linux, the command is executed immediately turn by turn. However, sometimes you will want to postpone after executing some commands before another or provide enough time for the system to produce the expected results. In this article, I will show you how to use bash sleep command to delay command execution in Linux.

What is sleep command?

This is a command in UNIX/Linux is used to suspend the calling the process of the next command for specific amount of time. This command is extremely useful when the following command depends on the successful completion of the previous.

How to use sleep command?

The syntax of sleep command is very simple:

sleep [number]

By default, the system reads the number parameter after sleep as the number of seconds to deplay.

For example, with the following code will sleep execution for 5 seconds

sleep 5

To specify other time units, use the following syntax:

sleep [number][unit]

In the above syntax, you can define multiple time units to delay executing command and sleep command also accepts float numbers. For example: if we want to delay 1 day, 2 hours, 5 minutes and 15.5 seconds together, then I will use the following command:

sleep 1d 2h 5m 15.5s

To stop the sleep command after starting and before ending, you could press Ctrl + C to stop it.

To see more information about this command, type this command:

sleep --help

To check sleep version on Linux, use the following command:

sleep --version

Bash sleep examples

Example 1: Set up an alarm

Instead of using smartphone or real alarm, you could use bash script to be an alarm to play a mp3 file after amount of time. And in this example, we will use mplayer to play the song:

sleep 1h 20m && mplayer alarm.mp3

Example 2: Counter

In this example, we will use bash script to be a counter with the following code:

#!/bin/bash
delay=1
for i in {1..1000};
do
echo $i
sleep delay
done

Example 3: Delay time for complete operation

Sometimes, you need to use bash script to call the other script or wait for process ID to be killed. Then, use sleep command to prevent executing the other script before process ID is killed.

while kill -0 $BACK_PID ; do
    echo "Waiting for the process to end"
    sleep 1
done

The command  kill -0 $BACK_PID is to check if process ID is kill, it will pass the while loop.

Conclusion

In this tutorial, we have shown you what is sleep command and some examples about how to use sleep command to pause the execution of the commands in a sequence.

Previous articleBash concatenate strings in text processing
Next articleHow to use unzip command in Linux