Skip to content
Home » Stop & Go with the Bash Sleep Command

Stop & Go with the Bash Sleep Command

The Bash Sleep Command is a built-in function of the Linux Bash shell that allows you to pause the execution of your scripts or terminal commands for a specified amount of time.

Practical Use-Cases for the Bash Sleep Command

1. Delay the Execution of Scripts

You can use the sleep command to delay the execution of your scripts, making them run at specific times or intervals. For example, you can use the following code to run a script every 30 minutes:

while true; do
   ./my_script.sh
   sleep 1800
done

2. Pause Scripts for a Specific Amount of Time

You can also use the sleep command to pause a script for a specific amount of time, allowing you to introduce pauses in your scripts to handle complex or time-sensitive processes. For example, you can use the following code to pause a script for 10 seconds:

echo "Pausing for 10 seconds..."
sleep 10
echo "Done."

3. Pause Terminal Commands

In addition to scripts, you can also use the sleep command to pause terminal commands, allowing you to run commands in a specific order or to introduce delays between commands. For example, you can use the following code to pause between running two terminal commands:

echo "Running command 1..."
command1
sleep 5
echo "Running command 2..."
command2

5 Tips for Using the Bash Sleep Command

  1. Remember that sleep time is specified in seconds, so use sleep 10 to pause for 10 seconds, sleep 60 to pause for 1 minute, and so on.
  2. You can use floating-point numbers to specify a sleep time with decimals, for example, sleep 0.5 for half a second.
  3. You can use the sleep command in combination with other commands, for example, you can use sleep 10; command1 to run command1 after a 10-second delay.
  4. The sleep command is not affected by signals, so you can use it to wait for long periods of time without being interrupted by signals such as SIGINT or SIGTERM.
  5. The sleep command is supported in most shell environments, including the Bourne shell, Z shell, and Korn shell, so you can use it in scripts and terminal commands on a wide range of systems.

Challenge

Try writing a script that uses the sleep command to print the current time every 5 seconds, until you stop the script. This is a great way to test your understanding of the sleep command and get familiar with using it in a script. Happy scripting!

Leave a Reply

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

eighteen − 14 =