Linux sleep in bash

Using Linux Sleep Command in Bash Scripts

This tutorial shows you how to use sleep commands and its various options in bash scripts.

Linux sleep command is one of the simplest commands out there. As you can guess from the name, its only function is to sleep. In other words, it introduces a delay for a specified time.

So, if you use the sleep command with x and the next command can only be run after x seconds.

Sleep command has a simple syntax:

In here, the suffix could be:

  • s for seconds. This is the default.
  • m for minutes.
  • h for hours.
  • d for days.

Let’s see some examples of the sleep command.

Bash sleep command Examples

Though you can use it in a shell directly, the sleep command is commonly used to introduce a delay in the execution of a bash script. I am going to show the usage of sleep command through sample bash scripts.

Sleep command without suffix counts in seconds

Suppose you want pause your bash script for 5 seconds, you can use sleep like this:

In a sample bash script, it could look like this:

!/bin/bash echo "Sleeping for 5 seconds…" sleep 5 echo "Completed"

If you run it with the time command, you’ll see that the bash script actually ran for (a slightly) more than 5 seconds.

time ./sleep.sh Sleeping for 5 seconds… Completed real 0m5.008s user 0m0.000s sys 0m0.007s

Sleep command with minute or hour or day suffix

You can specify the sleep time in minutes in the following way:

This will pause the script/shell for one minute. If you want to delay the script in hours, you can do that with the h option:

Even if you want to pause the bash script for days, you can do that with the d suffix:

This could help if you want to run on alternate days or week days.

Sleep command with a combination of second, minute, hour and day

You are not obliged to use only one suffix at a time. You can use more than one suffix and the duration of the sleep is the sum of all the suffix.

For example, if you use the follow command:

Читайте также:  Android hacks kali linux

This will keep the script waiting for 1 hour, 10 minutes and 5 seconds. Note that the s suffix is still optional here.

Bonus Tip: Sleep less than a second

You might have noticed that the smallest unit of time in the sleep command is second. But what if your bash script to sleep for milliseconds?

The good thing is that you can use floating point (decimal points) with sleep command.

So if you want to introduce a 5 milliseconds pause, use it like this:

You can also use decimal points with other suffixes.

It will introduce a delay of 1 hour, 37 minutes and 30 seconds.

I hope you didn’t sleep while reading these examples of sleep command 😉

If you are interested in shell scripting, perhaps you would like reading about string comparison in bash as well. If you have questions or suggestions, please feel free to ask.

Источник

Команда сна Linux (приостановка сценария Bash)

sleep — это утилита командной строки, которая позволяет приостанавливать вызывающий процесс на определенное время. Другими словами, команда sleep приостанавливает выполнение следующей команды на заданное количество секунд.

Команда sleep полезна при использовании в сценарии оболочки bash, например, при повторной попытке неудачной операции или внутри цикла.

В этом руководстве мы покажем вам, как использовать команду sleep в Linux.

Как использовать команду sleep

Синтаксис команды sleep следующий:

NUMBER может быть положительным целым числом или числом с плавающей запятой.

SUFFIX может быть одним из следующих:

Если суффикс не указан, по умолчанию используются секунды.

Когда даны два или более аргумента, общее количество времени эквивалентно сумме их значений.

Вот несколько простых примеров, демонстрирующих, как использовать команду sleep :

Примеры сценариев Bash

В этом разделе мы рассмотрим несколько основных сценариев оболочки, чтобы увидеть, как используется команда sleep .

#!/bin/bash # start time date +"%H:%M:%S" # sleep for 5 seconds sleep 5 # end time date +"%H:%M:%S" 

Когда вы запустите сценарий, он напечатает текущее время в формате HH:MM:SS . Затем команда sleep приостанавливает скрипт на 5 секунд. По истечении указанного периода времени последняя строка сценария выводит текущее время.

Результат будет выглядеть примерно так:

Давайте посмотрим на более сложный пример:

#!/bin/bash while : do if ping -c 1 ip_address &> /dev/null then echo "Host is online" break fi sleep 5 done 

Скрипт каждые 5 секунд проверяет, находится ли хост в сети или нет. Когда хост переходит в онлайн, скрипт уведомит вас и остановится.

  • В первой строке мы создаем бесконечный while цикл .
  • Затем мы используем команду ping чтобы определить, доступен ли хост с IP-адресом ip_address или нет.
  • Если хост доступен, сценарий выдаст эхо «Хост в сети» и завершит цикл.
  • Если хост недоступен, команда sleep приостанавливает скрипт на 5 секунд, а затем цикл начинается с начала.

Выводы

Команда sleep — одна из самых простых команд Linux. Он используется для приостановки выполнения следующей команды на заданное время.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

Команда sleep в bash: делаем задержки в скриптах

При написании shell-скрипта может возникнуть необходимость создать в нем паузу в несколько секунд перед выполнением очередного шага. Например, чтобы скрипт «подождал», пока завершится какой-то процесс, или сделал паузу перед повторной попыткой выполнить неудавшуюся команду.

Читайте также:  Linux find exec path

Для этого существует очень простая команда sleep .

Как используется команда sleep в bash

Sleep — универсальная команда с простым синтаксисом. Все, что нужно сделать, это набрать sleep N . Это поставит ваш скрипт на паузу на N секунд. Секунды можно указывать в целых положительных числах или в числах с плавающей запятой.

Рассмотрим базовый пример:

echo "Hello there!" sleep 2 echo "Oops! I fell asleep for a couple seconds!"

Результат работы этого скрипта выглядит так:

Аналогично можно использовать число с плавающей запятой: это позволит указать доли секунды. Например, sleep .8 приостановит работу скрипта на 0,8 с.

Вот и все, что можно сказать о работе команды sleep на базовом уровне!

Что нужно иметь в виду, используя команду sleep

По умолчанию время для sleep указывается в секундах, поэтому в примере мы не указывали единицы измерения времени.

На некоторых типах машин (конкретно — BSD и MacOS) время вообще указывается исключительно в секундах. В других Unix-подобных операционных системах скорее всего будут поддерживаться и другие единицы времени:

С командой sleep также можно использовать больше одного аргумента. Если вы укажете два или больше чисел, задержка будет соответствовать их сумме.

Например, указав sleep 2m 30s , вы создадите паузу на 2,5 минуты. Имейте в виду, что в MacOS или BSD для такого результата нужно написать sleep 150 , поскольку в этих ОС время указывается только в секундах, а 2,5 мин = 150 с.

Итоги

Команда sleep — удобный способ добавить паузу в ваш bash-скрипт. В сочетании с другими командами sleep может помочь запускать операции в правильном порядке, делать паузы между попытками соединения с сайтами и т. п. В общем, этот инструмент точно стоит добавить в свой набор!

Источник

How to Use the Linux sleep Command with Examples

When the user issues a multiple command sequence in Linux, the commands execute immediately one after another or concurrently (e.g., the tee command). However, sometimes it is necessary to postpone the execution of commands and provide enough time for the system to produce the expected results.

In this tutorial, you will learn how to use the Linux sleep command to delay command execution in the terminal and shell scripts.

How to Use the Linux sleep Command with Examples

What Does the Linux sleep Command Do?

The sleep command suspends the calling process of the next command for a specified amount of time. This property is useful when the following command’s execution depends on the successful completion of a previous command.

Linux sleep Command Syntax Explained

The syntax of the sleep command is simple:

Using the sleep command to introduce a 5-second delay in the terminal

In the example above, after sleep 5 was executed, the second command prompt appeared with a 5-second delay.

By default, the system reads the number after sleep as the number of seconds. To specify other time units, use the following syntax:

Using the sleep command to introduce a longer delay in the terminal

The sleep command accepts floating-point numbers. It allows multiple values, which are all added together to calculate the duration of sleep .

Читайте также:  Отформатировать диск при установке линукс

To stop sleep after it started and before the specified waiting period ends, press Ctrl + C .

To see help for the sleep command, type:

Linux sleep Command Examples

The following sections contain examples of using the sleep command in the terminal or shell scripts.

Note: The sleep command is designed to work in combination with other Linux commands. For a list of available Linux commands, download our free Linux Commands Cheat Sheet.

Set up an Alarm

Use sleep to tell the system to play an mp3 file after a certain amount of time. The example uses mplayer:

sleep 7h 30m && mplayer alarm.mp3

Delay Commands in Terminal

sleep is useful for enforcing a time between the execution of two commands. The following example makes echo commands execute in one-second intervals:

sleep 1 && echo "one" && sleep 1 && echo "two"

Introducing a one-second delay between command execution using the sleep command

Assign a Variable to the sleep Command

It is possible to assign a variable to the sleep command. Consider the following shell script:

#!/bin/bash SLEEP_INTERVAL="30" CURRENT_TIME=$(date +"%T") echo "Time before sleep: $" echo "Sleeping for $ seconds" sleep $ CURRENT_TIME=$(date +"%T") echo "Time after sleep: $"

The script defines a variable called SLEEP_INTERVAL whose value is later used as an argument to the sleep command. The output of this example script shows that the execution lasted 30 seconds:

Output of a script that shows the current time at the beginning and end of the execution

Define Check Intervals

The following example illustrates the use of the sleep command in a script that checks whether a website is online. The script stops if it successfully pings a website, and sleep introduces a 10-second delay between unsuccessful pings.

#!/bin/bash while : do if ping -c 1 www.google.com &> /dev/null then echo "Google is online" break fi sleep 10 done

A script that checks availability of a website outputs a message that the website is online

Allow Time for Operation Completion

You may be running a bash script that internally calls two other bash scripts – one that runs tests in the background and another that prints the results. Use sleep to prevent the second script from printing the wrong results if it executes before the completion of the first script:

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

The kill -0 $BACK_PID command checks if the first script’s process is still running. If it is, it prints the message and sleeps for 1 second before checking again.

Predict Latency

Use sleep to allow latency of certain command executions. The script snippet below shows how sleep gives the CPU enough time to perform the calculation before the next iteration.

After reading this tutorial, you should know how to use the Linux sleep command to pause the execution of the commands in a sequence.

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

Источник

Оцените статью
Adblock
detector