3 Ways How to ‘Sleep’ in a Linux Bash Shell Script

sleep in shell script

Shell scripting is a powerful programming method used to automate tasks in Unix and Linux systems. An integral part of shell scripting is the ‘sleep‘ command, often used to pause the execution of a script for a specified amount of time. Its usage helps manage system resources better and control script execution flow.

Understanding Sleep Command in Shell Scripting

The sleep command’s syntax is straightforward: sleep NUMBER[SUFFIX]. NUMBER is the time duration, and SUFFIX may be ‘s’ for seconds, ‘m’ for minutes, ‘h’ for hours, or ‘d’ for days. Detailed documentation can be found on the Sleep Command Manual. This command becomes invaluable when scripts need to wait before moving on to the next instruction, helping avoid system overload or timing problems.

5 Examples of Using the Linux ‘Sleep’ Command

Example #1: Basic usage of ‘sleep’

In the example below, a 3 second pause (sleep) will occur between the output of the first message and the second message.

echo "Starting script..."; sleep 3; echo "This message displays after 3 seconds."

Example #2: Using ‘sleep’ inside of a ‘for’ loop

In the example below, the ‘for’ loop will execute 5 times, but pausing (sleeping) for 1 second between each iteration.

for i in {1..5}; do echo "Loop $i"; sleep 1; done;

Example #3: Using Sleep Command in Background Processes

You can use the sleep command with background processes. In the following example, two processes are started in the background with different sleep times. The wait command is used to hold the script until both background processes are completed.

echo "Background job 1 (sleeps for 5 seconds) starts now...";
sleep 5 &
echo "Background job 2 (sleeps for 2 seconds) starts now...";
sleep 2 &
echo "Both background jobs are complete.";

Common Errors and Troubleshooting with Sleep Command

Some common errors stem from incorrect syntax or improper use within scripts. For instance, negative or non-numeric values will cause errors. Decimal values are allowed. In case a script hangs indefinitely, a Ctrl+C command will interrupt the sleep command and end the script. Tips for effective troubleshooting include validating input parameters, using proper timing intervals, and understanding the execution environment.

See also  Solution: incompatible implicit declaration of built-in function 'bzero'


What’s the purpose of Sleep Command in Shell Script?

It’s primarily used to pause script execution for a specified period.

How can I interrupt a Sleep Command?

Use the Ctrl+C command in the terminal.

Can I use decimal numbers with Sleep Command?

Yes, decimal values like sleep 0.5s are allowed.

What happens if I use a negative number with the Sleep Command?

It’ll cause an error as negative values are not valid.

Support us & keep this site free of annoying ads.
Shop Amazon.com or Donate with Paypal

Leave a Comment