Bash script countdown timer needs to detect any key to continue

后端 未结 2 618
夕颜
夕颜 2020-12-06 06:54

I need to listen for any key press in a countdown timer loop. If any key is pressed then the countdown timer should break out of it\'s loop. This mostly works except for t

相关标签:
2条回答
  • 2020-12-06 07:21

    The problem is that read would by default consider a newline as a delimiter.

    Set the IFS to null to avoid reading upto the delimiter.

    Say:

    IFS= read -s -N 1 -t 1 key
    

    instead and you'd get the expected behavior upon hitting the Enter key during the read.

    0 讨论(0)
  • 2020-12-06 07:23

    I think based on the return code of read, there is a work around for this problem. From the man page of read,

    The return code is zero, unless end-of-file is encountered, read times out,
    or an invalid file descriptor is supplied as the argument to -u.
    

    The return code for timeout seems to be 142 [verified in Fedora 16]

    So, the script can be modified as,

    #!/bin/bash
    for (( i=30; i>0; i--)); do
        printf "\rStarting script in $i seconds.  Hit any key to continue."
        read -s -n 1 -t 1 key
        if [ $? -eq 0 ]
        then
            break
        fi
    done
    echo "Resume script"
    
    0 讨论(0)
提交回复
热议问题