Search code examples
bashloopsbreak

Break a bash loop when [return] key is hit


Is it possible, in bash, to get out of a loop which doesn't wait for the user input when the [Return] key is hit?

Here is the kind of loop I mean. The key is [q]. I would like it to be [Return].

#!/bin/bash

stty -echo -icanon time 0 min 0 # Don't wait when read the input

i=1

while [ 1 ]; do

   echo -ne "$i\r"

   ((i+=1))

   read key

   if [ "$key" == "q" ]; then break; fi # If [q] is hit, get out of the loop

done

stty sane # Come back to the classic behavior

exit 0

Solution

  • To check that the user pressed exactly Return (aka. Enter) and not something like Ctrl+d, simply check that the exit code is zero (since Ctrl+d and Ctrl+c will result in a non-zero exit code) and that the key is empty:

    if [ $? -eq 0 ] && [ -z "$key" ]
    then
        break
    fi