How to Add Time Delay in Shell Script

How to Add Time Delay in Shell Script

Shell Scripts allow you to easily automate tasks and processes in Linux. Often while working with shell scripts you may need to add time delay in shell script, so that it pauses for sometime before proceeding with execution. This is really useful if your shell script’s last command takes some time to produce result and its next command depends on this output. In such cases, if the next command is run before the output is even generated then it may lead to undesirable results. In this article, we will learn how to add time delay in shell script in Linux.

How to Add Time Delay in Shell Script

Almost every Linux shell supports sleep command that allows you to pause shell script for a certain amount of time as per your requirement. Here is its syntax.

sleep NUMBER[SUFFIX]

In the above command, you need to specify the time delay as number to indicate the length of delay, followed by suffix s for seconds, m for minutes, h for hours and d for days. If you do not specify any suffix, it will assume the time delay to be in seconds. Here is the command to introduce a sleep delay of 5 minutes.

sleep 5m

Now let us create a simple shell script to test the time delay command. Create an empty shell script in text editor such as vi editor using the following terminal command.

# vi test.sh

Add the following line to specify the execution environment.

#!/bin/bash

Then add the following lines to simply print a line before calling sleep command, followed by the actual sleep command to pause for 5 seconds, and finally print a line after sleep command.

echo "Before sleep"
sleep 5s
echo "After sleep"

Save and exit the code editor. Make it executable with the following command.

# chmod +x test.sh

Run your script with the following command.

# ./test.sh

The above command will print ‘Before sleep’ immediately on script execution, then it will wait for 5 seconds and then print ‘After sleep’.

In this article, we have learnt how to add time delay in shell script.

Also read:

How to Import Files from Another Folder in Python
How to Get All Possible Combinations of Python List
How to Iterate Over Python Dictionaries
How to List All Files in Directory in Python
How to Use Variable in SQL Query in Python

Leave a Reply

Your email address will not be published. Required fields are marked *