I want to write a script to run a program after X seconds, it can be stopped if user press Enter
But it cannot detect whether user pressed Enter key or no input
#!/bin/bash
seconds=$((5))
holder='000'
while [ $seconds -gt 0 ]; do
if [[ $holder = "" ]]; then
echo "Stop"
exit
else
echo "Start in $seconds seconds, Press Enter to stop"
fi
IFS= read -r -t 1 -n 1 -s holder && var="$holder"
: $((seconds--))
done
echo Start
CodePudding user response:
If timeout happens, read
fails (i.e. returns a non-zero return code). So it is as simple as this:
if read -t 1
then
echo Enter pressed
else
echo Timeout happened
fi
So in your case, something like this, maybe?
seconds=5
while [[ "$seconds" -gt 0 ]]; do
echo "Start in $seconds seconds, Press Enter to stop"
if read -t 1 -s
then
echo Stop
exit
else
((seconds--))
fi
done
echo Start