Bash 读取退格键行为问题

标签 bash backspace

在 bash 中使用 read 时,按退格键不会删除输入的最后一个字符,但会在输入缓冲区中附加一个退格键。有什么办法可以更改它,以便删除从输入中删除最后键入的键吗?如果是怎么办?

如果有任何帮助的话,这是我正在使用的一个简短的示例程序:

#!/bin/bash

colour(){ #$1=text to colourise $2=colour id
        printf "%s%s%s" $(tput setaf $2) "$1" $(tput sgr0)
}
game_over() { #$1=message $2=score      
        printf "\n%s\n%s\n" "$(colour "Game Over!" 1)" "$1"
        printf "Your score: %s\n" "$(colour $2 3)"
        exit 0
}

score=0
clear
while true; do
        word=$(shuf -n1 /usr/share/dict/words) #random word from dictionary 
        word=${word,,} #to lower case
        len=${#word}
        let "timeout=(3+$len)/2"
        printf "%s  (time %s): " "$(colour $word 2)" "$(colour $timeout 3)"
        read -t $timeout -n $len input #read input here
        if [ $? -ne 0 ]; then   
                game_over "You did not answer in time" $score
        elif [ "$input" != "$word" ]; then
                game_over "You did not type the word correctly" $score;
        fi  
        printf "\n"
        let "score+=$timeout" 
done

最佳答案

选项 -n nchars 将终端转换为原始模式,因此最好的机会是依赖 readline (-e) [docs] :

$ read -n10 -e VAR

顺便说一句,不错的主意,尽管我会把单词的结尾留给用户(按 return 是下意识的 react )。

关于Bash 读取退格键行为问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4196161/

相关文章:

linux - 如何在不丢失尾随零的情况下使用 jq 获取纬度和经度?

java - 如何在 Android 上制作一个显示退格 (⌫) 字符的按钮?

android - 使用 TextWatcher 时退格键无法正常工作

ios - 检测空 UITextField 中的退格键

Javascript:如何从 div 或字符串中删除最后一个字符?

c -\b 是如何实现的?

linux - 在 Bash 中使用 shutdown 命令时出错

linux - 用 UNIX 时间戳替换日期,同时保留该行的其余部分

linux - 如何使用 SED 删除第 5 个和第 6 个分隔符之间的值?

linux - 在 bash 中提取特定单词