Output something (in a loop) until a key is pressed

Maybe this helps you. I integrated both of them, with slight modifications though. Here's the result.

BEGIN=$(date +%s)

echo Starting Stopwatch...
echo Press Q to exit.

while true; do
    NOW=$(date +%s)
    let DIFF=$(($NOW - $BEGIN))
    let MINS=$(($DIFF / 60))
    let SECS=$(($DIFF % 60))
    let HOURS=$(($DIFF / 3600))
    let DAYS=$(($DIFF / 86400))

    # \r  is a "carriage return" - returns cursor to start of line
    printf "\r%3d Days, %02d:%02d:%02d" $DAYS $HOURS $MINS $SECS

# In the following line -t for timeout, -N for just 1 character
    read -t 0.25 -N 1 input
    if [[ $input = "q" ]] || [[ $input = "Q" ]]; then
# The following line is for the prompt to appear on a new line.
        echo
        break 
    fi
done

As you can see, I put the second script in place of the sleep command in the former first one. The time-out in read now bears the time lapse function. Notice that the -N option is needed for read not to wait for Enter and react as soon as the first key has been pressed.

Tags:

Shell Script