BASH: 监听用户输入而不等待其他进程
BASH: Listening for user input without waiting to do other processes
好的,我有一个简单的脚本,其结构如下。我有这个子流程,它会 运行 无限期。截至目前,它只会在用户手动终止进程时停止。我想知道是否有一种方法可以在不卡在 read
行的情况下收听用户的输入。也就是说,子进程在运行ning的时候,在后台,看用户是否在终端输入"quit\n
"
...
if [[ option = "3" ]]; then
while [2 -lt 4]; #THIS IS WHERE I WANT TO CHANGE TO LISTENING FOR INPUT TO QUIT
#Some sub process that continues to run
done
fi
....
感谢您的帮助!抱歉,如果措辞不当,我想不出更好的方式来描述这个问题。至于我的头脑风暴尝试,我知道可以只在 while
条件下使用一个变量并说这样做直到它等于 "quit",但是将该变量设置为输入是我迷路的地方。
不确定我是否理解正确,但您正在寻找这样的东西吗?
while [[ 2 -lt 4 ]] ; do
read -t .1 user_input
[[ ${user_input} == "exit" ]] && exit 0
done
或者更简单:
unset user_input
while [[ "${user_input}" != "exit" ]] ; do
read -t .1 user_input
done
一般来说,您可以通过 read -t
.
实现您想要的效果
-t timeout
Cause read to time out and return failure if a complete line of input (or a spec‐
ified number of characters) is not read within timeout seconds. timeout may be a
decimal number with a fractional portion following the decimal point. This
option is only effective if read is reading input from a terminal, pipe, or other
special file; it has no effect when reading from regular files. If read times
out, read saves any partial input read into the specified variable name. If
timeout is 0, read returns immediately, without trying to read any data. The
exit status is 0 if input is available on the specified file descriptor, non-zero
otherwise. The exit status is greater than 128 if the timeout is exceeded.
好的,我有一个简单的脚本,其结构如下。我有这个子流程,它会 运行 无限期。截至目前,它只会在用户手动终止进程时停止。我想知道是否有一种方法可以在不卡在 read
行的情况下收听用户的输入。也就是说,子进程在运行ning的时候,在后台,看用户是否在终端输入"quit\n
"
...
if [[ option = "3" ]]; then
while [2 -lt 4]; #THIS IS WHERE I WANT TO CHANGE TO LISTENING FOR INPUT TO QUIT
#Some sub process that continues to run
done
fi
....
感谢您的帮助!抱歉,如果措辞不当,我想不出更好的方式来描述这个问题。至于我的头脑风暴尝试,我知道可以只在 while
条件下使用一个变量并说这样做直到它等于 "quit",但是将该变量设置为输入是我迷路的地方。
不确定我是否理解正确,但您正在寻找这样的东西吗?
while [[ 2 -lt 4 ]] ; do
read -t .1 user_input
[[ ${user_input} == "exit" ]] && exit 0
done
或者更简单:
unset user_input
while [[ "${user_input}" != "exit" ]] ; do
read -t .1 user_input
done
一般来说,您可以通过 read -t
.
-t timeout Cause read to time out and return failure if a complete line of input (or a spec‐ ified number of characters) is not read within timeout seconds. timeout may be a decimal number with a fractional portion following the decimal point. This option is only effective if read is reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If read times out, read saves any partial input read into the specified variable name. If timeout is 0, read returns immediately, without trying to read any data. The exit status is 0 if input is available on the specified file descriptor, non-zero otherwise. The exit status is greater than 128 if the timeout is exceeded.