Pause bash script linux

What is the Linux equivalent to DOS pause?

I have a Bash shell script in which I would like to pause execution until the user presses a key. In DOS, this is easily accomplished with the pause command. Is there a Linux equivalent I can use in my script?

10 Answers 10

user@host:~$ read -n1 -r -p "Press any key to continue. " key [. ] user@host:~$ 

The -n1 specifies that it only waits for a single character. The -r puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn’t register until you hit the next key. The -p specifies the prompt, which must be quoted if it contains spaces. The key argument is only necessary if you want to know which key they pressed, in which case you can access it through $key .

If you are using Bash, you can also specify a timeout with -t , which causes read to return a failure when a key isn’t pressed. So for example:

read -t5 -n1 -r -p 'Press any key in the next five seconds. ' key if [ "$?" -eq "0" ]; then echo 'A key was pressed.' else echo 'No key was pressed.' fi 

Strictly speaking, that would be «Enter any non-NUL character to continue» . Some keys don’t send any character (like Ctrl . ) and some send more than one (like F1 , Home . ). bash ignores NUL characters.

Usually it’s a better idea to ask for a specific key like enter, space or Y. «ANY» can be confusing to some users, there is a TAB-key so why no ANY-key and for sure there are keys that are potentially dangerous like ESCAPE, CTRL, CMD, the power button, etc. This isn’t so relevant anymore today, because nowadays the console is usually only used by advanced computer users that will interpret «ANY key» correctly. The Apple 2 Design Manual, tough quite old, has an interesting section devoted to this subject (apple2scans.net/files/1982-A2F2116-m-a2e-aiiedg.pdf).

If you instead use the message Press a key to continue. then even novice users will be able to find the a key and press it ;o)

This will have issues with command | myscript.sh or myscript.sh | command . See this answer for a solution.

If anyone gets read: 1: read: Illegal option -n make sure to wrap your command in bash -c ‘command && command’ etc. as that error is likely from sh . I am doing this in a Lando wrapper command.

I use these ways a lot that are very short, and they are like @theunamedguy and @Jim solutions, but with timeout and silent mode in addition.

Читайте также:  Linux open console hotkey

I especially love the last case and use it in a lot of scripts that run in a loop until the user presses Enter .

Commands

read -rsp $'Press enter to continue. \n' 
read -rsp $'Press escape to continue. \n' -d $'\e' 
read -rsp $'Press any key to continue. \n' -n 1 key # echo $key 
read -rp $'Are you sure (Y/n) : ' -ei $'Y' key; # echo $key 
read -rsp $'Press any key or wait 5 seconds to continue. \n' -n 1 -t 5; 
read -rst 0.5; timeout=$? # echo $timeout 

Explanation

-r specifies raw mode, which don’t allow combined characters like «\» or «^».

-s specifies silent mode, and because we don’t need keyboard output.

-p $’prompt specifies the prompt, which need to be between $’ and ‘ to let spaces and escaped characters. Be careful, you must put between single quotes with dollars symbol to benefit escaped characters, otherwise you can use simple quotes.

-d $’\e specifies escappe as delimiter charater, so as a final character for current entry, this is possible to put any character but be careful to put a character that the user can type.

-n 1 specifies that it only needs a single character.

-e specifies readline mode.

-i $’Y specifies Y as initial text in readline mode.

-t 5 specifies a timeout of 5 seconds

key serve in case you need to know the input, in -n1 case, the key that has been pressed.

$? serve to know the exit code of the last program, for read, 142 in case of timeout, 0 correct input. Put $? in a variable as soon as possible if you need to test it after somes commands, because all commands would rewrite $?

Источник

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

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

Для этого существует очень простая команда 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-подобных операционных системах скорее всего будут поддерживаться и другие единицы времени:

Читайте также:  Linux сбросить настройки панели

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

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

Итоги

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

Источник

How do I pause my shell script for a second before continuing?

I have only found how to wait for user input. However, I only want to pause so that my while true doesn’t crash my computer. I tried pause(1) , but it says -bash: syntax error near unexpected token ‘1’ . How can it be done?

11 Answers 11

sleep .5 # Waits 0.5 second. sleep 5 # Waits 5 seconds. sleep 5s # Waits 5 seconds. sleep 5m # Waits 5 minutes. sleep 5h # Waits 5 hours. sleep 5d # Waits 5 days. 

One can also employ decimals when specifying a time unit; e.g. sleep 1.5s

If you get an «invalid time interval» you might want to check for your end of line setting, if you created your script with a Windows tool your end of line is «CR LF», you need to change it for Linux which is «LF» only. (Actually the error should be self explicit: invalid time interval ‘1\r’ here you can see the extra \r from the \r\n)

read -p "Press enter to continue" 

In Python (question was originally tagged Python) you need to import the time module

from time import sleep sleep(1) 

For shell script is is just

Which executes the sleep command. eg. /bin/sleep

So while not the right way to do it, you can combine the python answer with Bash by using python -c «import time; time.sleep(1)» instead of sleep 1 🙂

@BerryM. — Takes about 1.2 seconds when I try it. Python doesn’t start up instantly — you need to account for that. Make it python -c «import time; time.sleep(0.8)» instead. But then we need to factor in how long python startup actually takes. You need to run this: date +%N; python -c «import time; time.sleep(0)»; date +%N to determine how many nanoseconds python is taking to start. But that also includes some overhead from running date. Run this date +%N; date +%N to find that overhead. Python’s overhead on my machine was actually closer to 0.14 seconds. So I want time.sleep(0.86) .

Источник

Bash Sleep – How to Make a Shell Script Wait N Seconds (Example Command)

Veronica Stork

Veronica Stork

Bash Sleep – How to Make a Shell Script Wait N Seconds (Example Command)

When you’re writing a shell script, you may find that you need it to wait a certain number of seconds before proceeding. For example, you might want the script to wait while a process completes or before retrying a failed command.

Читайте также:  Linux show file process

To do this, you can use the very straightforward sleep command.

How to Use the Bash Sleep Command

Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.

Consider this basic example:

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

The result of this script will look like this:

Similarly, you could use a floating point number to represent fractions of seconds. For example, sleep .8 will pause your script for .8 seconds.

That’s it for the basic usage of the sleep command!

What to Keep in Mind When Using the Sleep Command

Sleep ‘s default unit of time is seconds, which is why we don’t have to specify a unit in the examples above.

On some types of machines (namely BSD systems and MacOS,) the only unit of time supported is seconds. Other Unix-like operating systems will likely support the following units of time:

It is also possible to use more than one argument with the sleep command. If there are two or more numbers included, the system will wait for the amount of time equivalent to the sum of those numbers.

For example, sleep 2m 30s will create a pause of 2 and a half minutes. Note that to achieve the same result on a MacOS or BSD machine, you would run the equivalent command sleep 150 , as 2 minutes and 30 seconds is equal to 150 seconds.

Conclusion

The sleep command is a useful way to add pauses in your Bash script. Used in conjunction with other commands, sleep can help you create a timed alarm, run operations in the correct order, space out attempts to connect to a website, and more. So put this simple yet powerful tool in your Bash toolbox and code on!

Veronica Stork

Veronica Stork

Veronica is a librarian by trade with a longtime computer programming habit that she is currently working on turning into a career. She enjoys reading, cats, and programming in React.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

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