- 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?
- 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
- Использование команды Sleep в скриптах Bash в Linux
- Примеры команды Sleep в Bash
- Команда sleep без суффикса считается в секундах
- Команда Sleep с суффиксом m, h или d
- Команда sleep с комбинацией секунд, минут, часов и дня
- Бонусный совет: спать меньше секунды
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
Источник
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:
Источник
Использование команды Sleep в скриптах Bash в Linux
Главное меню » Операционная система Linux » Использование команды Sleep в скриптах Bash в Linux
Команда sleep в Linux – одна из самых простых команд. Как видно из названия, его единственная функция – спать. Другими словами, он вводит задержку на указанное время.
Таким образом, если вы используете команду sleep с x, то следующая команда может быть запущена только через x секунд.
Команда Sleep имеет простой синтаксис:
Здесь суффикс может быть:
Давайте посмотрим несколько примеров команды sleep.
Примеры команды Sleep в Bash
Хотя вы можете использовать его непосредственно в оболочке, команда sleep обычно используется для введения задержки в выполнение сценария bash. Мы собираемся показать использование команды sleep через примеры сценариев bash.
Команда sleep без суффикса считается в секундах
Предположим, вы хотите приостановить ваш bash-скрипт на 5 секунд, вы можете использовать режим sleep следующим образом:
В примере скрипта bash это может выглядеть так:
Если вы запустите его с помощью команды time, вы увидите, что скрипт bash на самом деле работал (немного) более 5 секунд.
Команда Sleep с суффиксом m, h или d
Вы можете указать время sleep в минутах следующим образом:
Это приостановит скрипт/оболочку на одну минуту. Если вы хотите отложить сценарий на несколько часов, вы можете сделать это с помощью опции h:
Даже если вы хотите приостановить скрипт на несколько дней, вы можете сделать это с помощью суффикса d:
Это может помочь, если вы хотите работать в разные дни или дни недели.
Команда sleep с комбинацией секунд, минут, часов и дня
Вы не обязаны использовать только один суффикс за раз. Вы можете использовать более одного суффикса, и продолжительность sleep является суммой всех суффиксов.
Например, если вы используете следующую команду:
Это заставит скрипт ждать 1 час 10 минут и 5 секунд. Обратите внимание, что суффикс s здесь по-прежнему необязателен.
Бонусный совет: спать меньше секунды
Вы могли заметить, что наименьшая единица времени в команде sleep – секунда. Но что если ваш bash-скрипт будет спать в течение миллисекунд?
Хорошо, что вы можете использовать с плавающей точкой (десятичные точки) с командой sleep.
Поэтому, если вы хотите ввести паузу в 5 миллисекунд, используйте ее следующим образом:
Вы также можете использовать десятичные точки с другими суффиксами.
Будет введена задержка в 1 час 37 минут и 30 секунд.
Мы надеемся, что вы не спали, читая эти примеры команды sleep -).
Если у вас есть вопросы или предложения, пожалуйста, не стесняйтесь спрашивать.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник