[英]Bash script listen for key press to move on

So, I want to write a bash script that are a sequence of steps and ill identify it as "task#". However, each step is only completed and can run as long as the user wants.


Do task1
if keypressed stop task1 and move on #this is the part I need help with. There can be up to 10 of these move on steps. 
Do task2

kina like top; it keeps doing stuff until you hit q to quite, however, i want to move on to the next thing


2 个解决方案



you can use read builtin command with option -t and -n

你可以使用帶有選項-t和-n的read builtin命令

while :
    # TASK 1
    read -t 1 -n 1 key

    if [[ $key = q ]]

# TASK 2
date +%s



kev's great solution works well even in Bash 3.x., but it introduces a 1-second delay (-t 1) in every loop iteration.

kev的優秀解決方案即使在Bash 3.x中運行良好,但它在每次循環迭代中引入了1秒的延遲(-t 1)。

In Bash 3.x, the lowest supported value for -t (timeout) is 1 (second), unfortunately.

在Bash 3.x中,不幸的是,-t(超時)支持的最低值為1(秒)。

Bash 4.x supports 0 and fractional values, however:

Bash 4.x支持0和小數值,但是:

A solution that supports an arbitrary key such as q requires a nonzero -t value, but you can specify a value very close to 0 to minimize the delay:


# !! BASH 4.x+ ONLY

while :; do

  # Loop command

  # Check for 'q' keypress *waiting very briefly*  and exit the loop, if found.
  read -t 0.01 -rN 1 && [[ $REPLY == 'q' ]] && break


# Post-loop command
date +%s

Caveat: The above uses 0.01 as the almost-no-timeout value, but, depending on your host platform, terminal program and possibly CPU speed/configuration, a larger value may be required / a smaller value may be supported. If the value is too small, you'll see intermittent error setting terminal attributes: Interrupted system call errors - if anyone knows why, do tell us.

警告:上面使用0.01作為幾乎沒有超時的值,但是,根據您的主機平台,終端程序和可能的CPU速度/配置,可能需要更大的值/可能支持更小的值。如果該值太小,您將看到間歇性錯誤設置終端屬性:系統調用錯誤中斷 - 如果有人知道原因,請告訴我們。

Tip of the hat to jarno for his help with the following:


Using -t 0, works as follows, according to help read (emphasis added):

根據幫助閱讀(強調添加),使用-t 0,如下工作:

If TIMEOUT is 0, read returns immediately, without trying to read any data, returning success only if input is available on the specified file descriptor.


As of Bash v4.4.12, unfortunately, -t 0 seems to ignore -n / -N, so that only an ENTER keypress (or a sequence of keypresses ending in ENTER) causes read to indicate that data is available.
If anyone knows whether this is a bug or whether there's a good reason for this behavior, do let us know.

從Bash v4.4.12開始,遺憾的是,-t 0似乎忽略了-n / -N,因此只有一個ENTER按鍵(或一系列以ENTER結尾的按鍵)才會導致讀取指示數據可用。如果有人知道這是一個錯誤,還是有充分理由說明這種行為,請告訴我們。

Therefore, only with ENTER as the quit key is a -t 0 solution currently possible:

因此,只有使用ENTER作為退出鍵才是當前可能的-t 0解決方案:

# !! BASH 4.x+ ONLY

while :; do

  # Loop command

  # Check for ENTER keypress and, after clearing the input buffer
  # with a dummy `read`, exit the loop.
  read -t 0 -r && { read -r; break; }


# Post-loop command
date +%s



粤ICP备14056181号  © 2014-2021