Bash: How to end infinite loop with any key pressed?

前端 未结 6 757
长发绾君心
长发绾君心 2020-11-30 03:16

I need to write an infinite loop that stops when any key is pressed.

Unfortunately this one loops only when a key is pressed.

Ideas please?

#         


        
6条回答
  •  佛祖请我去吃肉
    2020-11-30 03:55

    Here is another solution. It works for any key pressed, including space, enter, arrows, etc.

    The original solution tested in bash:

    IFS=''
    if [ -t 0 ]; then stty -echo -icanon raw time 0 min 0; fi
    while [ -z "$key" ]; do
        read key
    done
    if [ -t 0 ]; then stty sane; fi
    

    An improved solution tested in bash and dash:

    if [ -t 0 ]; then
       old_tty=$(stty --save)
       stty raw -echo min 0
    fi
    while
       IFS= read -r REPLY
       [ -z "$REPLY" ]
    do :; done
    if [ -t 0 ]; then stty "$old_tty"; fi
    

    In bash you could even leave out REPLY variable for the read command, because it is the default variable there.

提交回复
热议问题