Debug School

rakesh kumar
rakesh kumar

Posted on

Bash Date Formatting and Bash Sleep

$ date
$ date +

d=date +%m-%d-%Y

d=date +%m-%Y

In this topic, you will understand how to use sleep command by using different bash scripts. Sleep is a command-line utility which allows us to suspend the calling process for a specified time. In other words, Bash sleep command is used to insert a delay or pause the execution for a specified period of time.

When the programmer needs to pause the execution of any command for the specific purpose, then this command can be used with the specific time value. One can set the delay amount by seconds (s), minutes (m), hours (h), and days (d). This command is especially useful when it is used within a bash shell script.

Sleep Command Syntax
Following is the syntax for the sleep command in Bash:

sleep number[suffix] 
Enter fullscreen mode Exit fullscreen mode

You can use any positive integer or fractional number as time value. A suffix is an optional part. You can apply any of the following as suffix:

s - seconds
m - minutes
h - hours
d - days
Enter fullscreen mode Exit fullscreen mode

Note: When there is no suffix, then the number is considered to be in seconds (by default).
When two or more arguments are specified, then the total amount of time will be considered as the time equivalent to the sum of their values.

Following are the few simple examples showing how to use sleep command:

Sleep for 9 seconds, use
sleep 9 or sleep 9s
Sleep for 0.5 seconds, use
sleep 0.5 or sleep 0.5s
Sleep for 2 minute and 30 seconds, use
sleep 2m 30s
Sleep for 8 hours
sleep 8h
Sleep for 2 days, 9 hours, 5 minute and 55 seconds, use
sleep 2d 9h 5m 55s
Enter fullscreen mode Exit fullscreen mode

Bash Scripts Example
We are going to explain the most basic example of sleep command in Bash.

Bash Script


# start time  
date +"%H:%M:%S"  

echo "wait for 9 seconds"  

# sleep for 9 seconds  
sleep 9s   
# you can also use "sleep 9" in place of "sleep 9s" because if there is no suffix, it is considered as "seconds".  

# end time  
date +"%H:%M:%S"  

echo "Task Completed"  
Enter fullscreen mode Exit fullscreen mode

Image description


Image description

How the script works
When we run the script, it will print the current time in HH:MM:SS format. Then the echo command will execute and print the message "wait for 9 seconds". Then the sleep command will execute and pause the script for 9 seconds. When the specified time period elapses, the next line of the script will again print the current time. Lastly, the echo command will print the message "Task Completed".

Similarly, you can run sleep command for minutes, hours, and days.

Top comments (0)