Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Press any key to abort in 5 seconds

Hi I'm trying to implement an event that will happen after a 5 second countdown, unless a key is pressed. I have been using this code, but it fails if I press enter or space. It fails in the sense that enter or space is detected as "".

echo "Phoning home..."
key=""
read -r -s -n 1 -t 5 -p "Press any key to abort in the next 5 seconds." key
echo
if [ "$key" = "" ]     # No Keypress detected, phone home.
     then python /home/myuser/bin/phonehome.py
     else echo "Aborting."
fi

After reading this post, Bash: Check if enter was pressed

I gave up and posted here. I feel like there must be a better way than what I have tried to implement.

like image 252
inkman Avatar asked Dec 24 '15 20:12

inkman


1 Answers

The read manual says:

The return code for read is zero, unless end-of-file is encountered or read times out.

In your case, when the user hits any key within allowed time you wish to abort else continue.

#!/bin/bash
if read -r -s -n 1 -t 5 -p "TEST:" key #key in a sense has no use at all
then
    echo "aborted"
else
    echo "continued"
fi

Reference: Read Manual
Note: The emphasis in the citation is mine.

like image 162
sjsam Avatar answered Nov 12 '22 16:11

sjsam