- Команда сна Linux (приостановка сценария Bash)
- Как использовать команду sleep
- Примеры сценариев Bash
- Выводы
- How to Use the Linux Sleep Command to Pause a BASH Script
- Want to slow down your BASH script? Use the sleep command
- What To Know
- An Example of Using the Sleep Command
- How to Use the Sleep Command
- An Example of Using the Sleep Command
- How to Use Sleep Command Switches
- Pause Terminal Commands with Sleep
- Как использовать команду Linux Sleep для приостановки сценария Bash
- How to Use the Linux Sleep Command to Pause a Bash Script
- В этом руководстве мы покажем вам, как использовать команду Linux sleep .
- Как использовать 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 (приостановка сценария 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. Он используется для приостановки выполнения следующей команды на заданное время.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
How to Use the Linux Sleep Command to Pause a BASH Script
Want to slow down your BASH script? Use the sleep command
What To Know
- Use the sleep command plus a time; s=seconds, m=minutes, h=hours, or d=days (for example, sleep 5s pauses the script for 5 seconds).
- Use man sleep for more.
This article explains how to use the Linux sleep command to pause a bash script, among other things. On its own, the sleep command isn’t very useful. However, as part of a script, it can be used in many ways. For example, you can use it to pause the script before retrying a command that failed the first time.
An Example of Using the Sleep Command
Imagine you have a script that processes files that were downloaded from another server. The script shouldn’t start the copy process until all the files finish downloading. The download process is performed by a separate script that runs before yours.
The script that copies the files may contain a loop to test whether all the files have downloaded (it does this by checking whether 50 files are found before starting the copy process).
There’s no point in the script testing constantly since this uses processor time. Instead, you might pause for a few minutes between each test before trying again. The sleep command is perfect in such circumstances.
How to Use the Sleep Command
To use the Linux sleep command, enter the following into the terminal window:
The above command makes the terminal pause for 5 seconds before returning to the command line.
The sleep command requires the keyword sleep, followed by the number you want to pause and the unit of measure.
You can specify the delay in seconds, minutes, hours, or days.
- s: Seconds
- m: Minutes
- h: Hours
- d: Days
When it comes to pausing a script for days, use a cron job to run the script at regular intervals, as opposed to having a script run in the background for days.
A cron job is a Linux command or script that you can schedule to run at a set time or day. These are useful for repeating tasks over a long period of time.
The number for the sleep command interval doesn’t have to be a whole number. You can also use floating-point numbers.
For example, the following syntax includes a fraction of a second:
An Example of Using the Sleep Command
The following script shows how to use the sleep command to make a terminal-based countdown clock:
#!/bin/bash
x=10
while [ $x -gt 0 ]
do
sleep 1s
clear
echo «$x seconds until blast off»
x=$(( $x — 1 ))
done
Here’s how this script works:
- The script sets the variable x to 10.
- The while loop continues to iterate while the value of x is greater than zero.
- The sleep command pauses the script for 1 second each time around the loop.
- The rest of the script clears the screen each iteration, displays the message, «x seconds until blast off,» and subtracts 1 from the value of x.
Without the sleep command, the script would zoom through, and the messages would display too quickly.
How to Use Sleep Command Switches
The sleep command only has a couple of switches.
The —help switch shows the help file for the sleep command. You can achieve the same thing by using the man command as follows:
The —version switch shows the version of the sleep command that’s installed on the system.
The information returned by the —version switch is as follows:
- Version number
- Copyright details
- License
- Authors
Pause Terminal Commands with Sleep
Another good use for the sleep command is to pause commands that you type in the terminal window.
If you want, you can type two commands in a row, waiting for the first one to finish before typing the second.
However, a faster approach is to type the two commands on one line, with a sleep command between each command:
$ cd /mydirectory/ && sleep 3 && ls
How this command works:
- The cd /mydirectory/ command changes the directory.
- The sleep 3 command waits three seconds for the cd command to finish.
- The ls command executes and displays the directory contents.
For a simple example like this, the sleep command only saves a little bit of time. However, if you have a long list of commands, the ability to type the commands on one line saves time.
Источник
Как использовать команду 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. Он используется для приостановки выполнения следующей команды на определенный промежуток времени.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
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:
Источник