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.