0

I was reading this thread: Bash script countdown timer needs to detect any key to continue

It seems I could implement something similar so that my script always starts out waiting x seconds for someone to hit a key. The thing I want to change is if they hit that key I want to skip to a specific part of my script.

How can I achieve this?

Karl Nicoll
  • 16,090
  • 3
  • 51
  • 65
Tony
  • 8,681
  • 7
  • 36
  • 55

1 Answers1

0

How about this (adapted from Sakthi Kumar's answer in the linked question):

#!/bin/bash

was_key_pressed=

for (( i=10; i>0; i--)); do
    printf "\rHit any key to show 'Foo', or wait $i seconds and 'Bar' will be displayed..."
    read -s -n 1 -t 1 key
    if [ $? -eq 0 ]
    then
        was_key_pressed="true"
        break
    fi
done
echo

if [ "${was_key_pressed}" ]; then
    echo "Foo"
else
    echo "Bar"
fi

The script uses a variable called was_key_pressed, and set's it's value to an empty string. Then, if a key is pressed in the read function, it sets the value of was_key_pressed to "true" and breaks out of the loop.

Once the loop has exited, the word "Foo" will be printed if a key was pressed by checking if was_key_pressed is still an empty string, otherwise "Bar" will be printed if no key was pressed.

Community
  • 1
  • 1
Karl Nicoll
  • 16,090
  • 3
  • 51
  • 65
  • I thought this was working as intended but it isn't and re-reading your explanation I think the problem is here: **otherwise both "Foo" and "Bar" will be printed.** where as I want only one or the other to be executed. How do I accomplish that? – Tony May 07 '14 at 20:20
  • @Tony - I've updated my answer based on your comment. Now "foo" will be executed if a key is pressed, otherwise "bar" will be printed. Let me know if that's what you wanted :-) – Karl Nicoll May 07 '14 at 20:52