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


echo "here's your message"
if [[sleep 3 || read -p "$*"]]

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.


1 Answer 1


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"
    echo "Can't wait anymore!"

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


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.'
  • Fantastic! Thank you, the first one worked perfectly for my purposes. Mar 20, 2015 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.