BASH function to read user input OR interrupt on timeout

bashread

I am trying to write a BASH function that will do x if program a or b finish.

example:

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

In this scenario:

a = 'sleep 3' which is supposed to run x after 3 seconds

b = 'read -p "$*"' which is supposed to run x upon providing any keyboard input.

x = 'clear' which clears the echo output if either the program times out with sleep or the user presses a key on the keyboard.

Best Answer

read has a parameter for timeout, you can use:

read -t 3 answer

If you want read to wait for a single character (whole line + Enter is default), you can limit input to 1 char:

read -t 3 -n 1 answer

After proper input, return value will be 0, so you can check for it like this:

if [ $? == 0 ]; then
    echo "Your answer is: $answer"
else
    echo "Can't wait anymore!"
fi

I guess there is no need to implement background jobs in your situation, but if you want to, here is an example:

#!/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.'
Related Question