- Как использовать команду Linux Sleep для приостановки сценария Bash
- How to Use the Linux Sleep Command to Pause a Bash Script
- В этом руководстве мы покажем вам, как использовать команду Linux sleep .
- Как использовать sleep команду
- Примеры скриптов на Bash
- Вывод
- Linux / UNIX: Bash Script Sleep or Delay a Specified Amount of Time
- Examples
- sleep Command Bash Script Example
- How can I pause my bash shell script for 5 second before continuing?
- Команда сна Linux (приостановка сценария Bash)
- Как использовать команду sleep
- Примеры сценариев Bash
- Выводы
- Bash add pause prompt in a shell script ( bash pause command )
- bash pause command under Linux / UNIX / macOS
- Bash add pause prompt in a shell script with bash pause command
- bash shell pause function
- Getting help about the read command
- Linux sleep command to pause a bash script
- How to use the sleep command
- Conclusion
Как использовать команду Linux Sleep для приостановки сценария Bash
How to Use the Linux Sleep Command to Pause a Bash Script
В этом руководстве мы покажем вам, как использовать команду Linux sleep .
sleep утилита командной строки, которая позволяет приостановить вызывающий процесс на указанное время Другими словами, sleep команда приостанавливает выполнение следующей команды на заданное количество секунд.
Команда sleep полезна, когда используется в сценарии оболочки bash, например, при повторной попытке сбойной операции или внутри цикла.
Как использовать sleep команду
Синтаксис sleep команды следующий:
SUFFIX Может быть одним из следующих:
- s — секунды (по умолчанию)
- m — минуты
- h — часов
- d — дни
Если суффикс не указан, по умолчанию используется значение секунд.
Когда задано два или более аргументов, общее количество времени эквивалентно сумме их значений.
Вот несколько простых примеров, демонстрирующих, как использовать sleep команду:
Спать в течение 0,5 секунд:
Сон в течение 2 минут и 30 секунд:
Примеры скриптов на Bash
В этом разделе мы рассмотрим несколько основных сценариев оболочки, чтобы увидеть, как используется sleep команда.
Когда вы запустите скрипт, он напечатает текущее время в HH:MM:SS формате. Затем sleep команда приостанавливает выполнение сценария на 5 секунд. По истечении указанного периода времени последняя строка скрипта печатает текущее время.
Вывод будет выглядеть примерно так:
Давайте посмотрим на более сложный пример:
Скрипт проверяет, находится ли хост в сети или нет, каждые 5 секунд. Когда хост выходит в сеть, скрипт уведомит вас и остановит.
Как работает скрипт:
- В первой строке мы создаем бесконечный while цикл .
- Затем мы используем ping команду, чтобы определить, ip_address доступен ли хост с IP-адресом или нет.
- Если хост доступен, сценарий отобразит «Хост подключен» и завершит цикл.
- Если хост недоступен, sleep команда приостанавливает выполнение сценария на 5 секунд, а затем цикл начинается с начала.
Вывод
Команда sleep является одной из самых простых команд Linux. Он используется для приостановки выполнения следующей команды на определенный промежуток времени.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
Linux / UNIX: Bash Script Sleep or Delay a Specified Amount of Time
H ow do I pause for 5 seconds or 2 minutes in my bash shell script on a Linux or Unix-like systems?
You need to use the sleep command to add delay for a specified amount of time. The syntax is as follows for gnu/bash sleep command:
sleep NUMBER[SUFFIX] [donotprint]
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | bash |
Est. reading time | 1m |
[/donotprint] Where SUFFIX may be:
- s for seconds (the default)
- m for minutes.
- h for hours.
- d for days.
Please note that the sleep command in BSD family of operating systems (such as FreeBSD) or macOS/mac OS X does NOT take any suffix arguments (m/h/d). It only takes arguments in seconds. So syntax for sleep command for Unix like system is:
sleep NUMBER
Examples
To sleep for 5 seconds, use:
sleep 5
Want to sleep for 2 minutes, use:
sleep 2m
Halt or sleep for 3 hours, use:
sleep 3h
More examples:
The most common usage are as follows:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Sample outputs from last while loop:
Animated gif.01: Sleep command in action
sleep Command Bash Script Example
Here is a simple example:
In this example, create the lock directory. I’m using [/\\:.-] here to ensure that we don’t use the same name that we are using for the .o file. Also, base the name on the expected object file name, since that is what matters with a parallel build.
How can I pause my bash shell script for 5 second before continuing?
Use the read command:
read -p «text» -t 5
read -p «Waiting five secs for Cloudflare to clear cache. » -t 5
echo «Generating pdf file now . »
Sample outputs:
Waiting five secs for Cloudflare to clear cache.
Generating pdf file now .
Where,
- -p «text» : Show the text without a trailing newline before time out.
- -t N : Set time out to 5 seconds.
For more info see bash command man page here and here or read it by typing the following man command:
$ man bash
$ man sleep
$ help read
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Команда сна Linux (приостановка сценария Bash)
sleep — это утилита командной строки, которая позволяет приостанавливать вызывающий процесс на определенное время. Другими словами, команда sleep приостанавливает выполнение следующей команды на заданное количество секунд.
Команда sleep полезна при использовании в сценарии оболочки bash, например, при повторной попытке неудачной операции или внутри цикла.
В этом руководстве мы покажем вам, как использовать команду sleep в Linux.
Как использовать команду sleep
Синтаксис команды sleep следующий:
NUMBER может быть положительным целым числом или числом с плавающей запятой.
SUFFIX может быть одним из следующих:
- s — секунды (по умолчанию)
- m — минуты
- h — часы
- d — дни
Если суффикс не указан, по умолчанию используются секунды.
Когда даны два или более аргумента, общее количество времени эквивалентно сумме их значений.
Вот несколько простых примеров, демонстрирующих, как использовать команду sleep :
Сон на 0,5 секунды:
Сон 2 минуты 30 секунд:
Примеры сценариев Bash
В этом разделе мы рассмотрим несколько основных сценариев оболочки, чтобы увидеть, как используется команда sleep .
Когда вы запустите сценарий, он напечатает текущее время в формате HH:MM:SS . Затем команда sleep приостанавливает скрипт на 5 секунд. По истечении указанного периода времени последняя строка сценария выводит текущее время.
Результат будет выглядеть примерно так:
Давайте посмотрим на более сложный пример:
Скрипт каждые 5 секунд проверяет, находится ли хост в сети или нет. Когда хост переходит в онлайн, скрипт уведомит вас и остановится.
Как работает скрипт:
- В первой строке мы создаем бесконечный while цикл .
- Затем мы используем команду ping чтобы определить, доступен ли хост с IP-адресом ip_address или нет.
- Если хост доступен, сценарий выдаст эхо «Хост в сети» и завершит цикл.
- Если хост недоступен, команда sleep приостанавливает скрипт на 5 секунд, а затем цикл начинается с начала.
Выводы
Команда sleep — одна из самых простых команд Linux. Он используется для приостановки выполнения следующей команды на заданное время.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
Bash add pause prompt in a shell script ( bash pause command )
M ost of you may be aware of old good DOS/2000/XP pause command. It is used to display the prompt while suspending the processing of a batch script. It is used within a computer batch file and allows the computer to pause the currently running batch file until the user presses any key. Let us see how to pause our bash based shell script for a given number of times in seconds/minutes/hours before continuing to next operation/command running on a Linux or Unix-like systems.
bash pause command under Linux / UNIX / macOS
There is no pause command under Linux/UNIX bash shell. You can easily use the read command with the -p option to display pause along with a message.
Bash add pause prompt in a shell script with bash pause command
The above will suspends processing of a shell script and displays a message prompting the user to press [Enter] (or any) key to continue. The last example will wait for 5 seconds before next command execute. We can pass the -t option to the read command to set time out value. By passing the -s we can ask the read command not to echo input coming from a terminal/keyboard as follows:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
bash shell pause function
You can create a function as follows:
Getting help about the read command
Linux sleep command to pause a bash script
We can also use the sleep command to pause the execution of the next command or task for a given number of seconds. The syntax is as follows:
sleep NUM
sleep NUM[suffix]
By default it will pause for NUMBER seconds but we can add [suffix] as follows:
- s for seconds (the default)
- m for minutes
- h for hours
- d for days
Unlike most implementations of sleep on Unix-like system that require NUMBER be an integer, GNU/pause command NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values.
How to use the sleep command
To sleep for 3 seconds, enter:
sleep 3
One can sleep for 0.8 seconds:
sleep 0.8
In this final example, sleep for 1 minute and 42 seconds:
sleep 1m 42s
Bash add pause prompt using the sleep command:
Please note that portable POSIX shell scripts must give sleep a single non-negative integer argument without a suffix. In other words the following is only valid:
sleep 10
Conclusion
Original DOS/XP pause command is an internal command. Use the above technique if you are migrating from DOS/Windows batch file scripting. Both the read command/sleep command used to pause the execution of the next action in script for a given amount of time. See GNU/sleep command man page here or by typing the following man command:
man sleep
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
What about SLEEP command?
Sleep puts a delay for a specified amount of time w/o a prompt. So you need to use read -p so that user can hit a key.
One small tip,
If you do this in a while loop that reads from a file.
e.g.
while read line
do
…..
read -p somevar
…..
done Gilles Allard Mar 5, 2007 @ 21:11
If you need an exact replacement for PAUSE you need to use:
read -n 1 -p prompt
without -n, read will require the ENTER key.
I’m not sure but -n may be a bash specific.
read -p “Press any key”. doesn’t provide the ‘pause’ behavior.
It requires ‘ENTER’ key to be pressed, so it becomes, ‘press ENTER key’ instead of ‘press any key’.
Thank you. I learned that the not so hard way. Trying it. 🙂
Using simply read to pause>nul can be quite useful too.
I ran into the need for pause in this simple bash script, where I pass a website as argument and the script tells me the password to the site from my personal password file. Note: one site and one password on each line, file mode should be 600.
The script is useful to have on my webserver which is always on and I can reach from work or anywhere whenever I need it.
/my_passwords.txt | grep $1; read; clear;
Hope this helps someone 🙂
Also gives me
4: read: arg count
(I needed to put in a “are you sure” message for windows users to be able to run scripts on a Linux box… who knows if it will help, but hey, at least it’s a start.)
Cool to know that that works out aswell!!
I believe the following is at least very close to the behavior of the pause command.
function pause() <
read -s -n 1 -p «Press any key to continue . . .»
echo
>
read is a good choice for pausing but, sometimes we are looking for — pause then continue command without user interference so i guess sleep is more realiable
Being a windows admin this was of great help.
- -n1 -> number of character it can read
- -t5 -> it will wait for 5 seconds the user to enter a char after 5 sec it will resume the flow
Hi,
I have one unix script file that has one command to execute a java program. That Java program is used to download a file from a server. After this command I have different commands (“hdiutil checksum -type CRC32 “) to execute on the downloaded file. My problem is that after executing the java command it is not waiting for the file to be downloaded from the server and executing that command and fails because still that file is not downloaded.
Can someone help me to resolve this issue. How should I wait fro the file to be downloaded then only it should execute the other commands?
Please help me to get out in to this situation as soon as possible…
for anyone writing any cli based php scripts, and who doesnt feel like installing the whole ncurses package JUST to get the ‘press enter to continue…’ functionality…
this method works great via
Thanks for script, I put it at the end of a function and it is helpful. How would I call a function when Enter is pressed? I tried the following but it didn’t work:
I want to write a program which pause execution when i enter “return key ” and start execution when i again enter “return key ” from where it is paused.
Please help me.
Thanks worked perfectly. Wonder why they don’t have this as a bash command…
The code worked except the comment should read “Press the ENTER key to continue…”.
Thank you!
This code worked for me well!
I am looking to pause the script multiple times. So, I used multiple pause statements after every 10 lines. It didn’t work.
Does anyone know why?
It’s not working for me. I’m not sure why. The loop just keeps going.
There is a way to cleanly do that on Linux:
Perfect, that’s exactly what I needed and the only approach that worked for me. Notice, that also this should read “Press …” instead of “any key”.
Sorry, previous one don’t properly works.
This do the job:
Источник