在Bash中不再按下键时停止命令

时间:2014-07-17 13:43:52

标签: bash sh

认为这会更明显,但我需要在按下按键时运行命令,并在不再按下时停止命令(SIGINT)。

例如:

#!/bin/bash

while [ F5 is being pressed ] ; do

    arecord -f cd -t wav

done

1 个答案:

答案 0 :(得分:1)

PlayShellkeys.sh转发,您可以:

#!/bin/bash

shopt -s extglob

KEYS_F5=$'\e[[E'
KEYS_XTERM_F5=$'\e[15~'

function keys_readonce {
    __V0='' __V1=''

    local A K
    local -a KEY=() S=() T=()

    for A; do
        case "$A" in
        +([[:digit:]]))
            T=(-t "$A")
            ;;
        -q|--quiet)
            S=(-s)
            ;;
        *)
            echo "Invalid argument: $A"
            exit 1
            ;;
        esac
    done

    local IFS=''

    if read -rn 1 -d '' "${T[@]}" "${S[@]}" K; then
        KEY[0]=$K

        if [[ $K == $'\e' ]]; then
            if [[ BASH_VERSINFO -ge 4 ]]; then
                T=(-t 0.05)
            else
                T=(-t 1)
            fi

            if read -rn 1 -d '' "${T[@]}" "${S[@]}" K; then
                case "$K" in
                \[)
                    KEY[1]=$K

                    local -i I=2

                    while
                        read -rn 1 -d '' "${T[@]}" "${S[@]}" "KEY[$I]" && \
                        [[ ${KEY[I]} != [[:upper:]~] ]]
                    do
                        (( ++I ))
                    done
                    ;;
                O)
                    KEY[1]=$K
                    read -rn 1 -d '' "${T[@]}" 'KEY[2]'
                    ;;
                [[:print:]]|$'\t'|$'\e')
                    KEY[1]=$K
                    ;;
                *)
                    __V1=$K
                    ;;
                esac
            fi
        fi

        __V0="${KEY[*]}"

        return 0
    fi

    return 1
}

while keys_readonce 5 && [[ $__V0 == "$KEYS_F5" || $__V0 == "$KEYS_XTERM_F5" ]]; do  ## 5 secs. timeout is optional
    # Do something
    :
done