BASH 函数读取用户输入或超时中断

Jay*_*ter 5 bash read

我正在尝试编写一个 BASH 函数,如果程序 a 或 b 完成,它将执行 x。

例子:

echomessage()
{
echo "here's your message"
if [[sleep 3 || read -p "$*"]]
then
   clear
fi
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下:

a = ' sleep 3' 应该在 3 秒后运行 x

b = ' read -p "$*"' 应该在提供任何键盘输入时运行 x 。

x = ' clear' 如果程序因睡眠超时或用户按下键盘上的键,则清除回显输出。

mad*_*eon 14

read 有一个超时参数,您可以使用:

read -t 3 answer
Run Code Online (Sandbox Code Playgroud)

如果要read等待单个字符(默认为整行 + Enter),可以将输入限制为 1 个字符:

read -t 3 -n 1 answer
Run Code Online (Sandbox Code Playgroud)

正确输入后,返回值将为0,因此您可以像这样检查它:

if [ $? == 0 ]; then
    echo "Your answer is: $answer"
else
    echo "Can't wait anymore!"
fi
Run Code Online (Sandbox Code Playgroud)

我想没有必要在您的情况下实施后台作业,但如果您愿意,这里有一个示例:

#!/bin/bash

function ProcessA() {
    sleep 1  # do some thing
    echo 'A is done'
}

function ProcessB() {
    sleep 2  # do some other thing
    echo 'B is done'
}

echo "Starting background jobs..."

ProcessA &  # spawn process "A"
pid_a=$!    # get its PID

ProcessB &  # spawn process "B"
pid_b=$!    # get its PID too

echo "Waiting... ($pid_a, $pid_b)"
wait  # wait for all children to finish

echo 'All done.'
Run Code Online (Sandbox Code Playgroud)