用于生成随机字母表的 Unix 命令

use*_*420 1 shell-script

我必须为这个程序编写一个脚本。中随机选择一个字母a-z。要求用户猜字母,将其与所选字母匹配。如果匹配,则显示“正确”,否则提示猜测的字母是否在所选字母的上方或下方。有人可以举例说明我如何在 shell 中执行此操作吗?

小智 6

巴什

BASH 非常适合这项工作,因为 BASH 可以通过使用轻松生成字母表,{a..z}并且 BASH 可以输入单个字符而无需按 ENTER

$ cat guesschar.bash 
c=$(echo {a..z} | tr -d ' ')
x=${c:$((RANDOM%26+1)):1}
while read -n1 -p'guess the char: ' ; do
        echo
        if [[ $REPLY < $x ]] ; then echo too low...
        elif [[ $REPLY > $x ]] ; then echo too high...
        else break
        fi
done
echo $x ... 'hit!'
$ bash guesschar.bash 
guess the char: m
too high...
guess the char: f
too low...
guess the char: j
too low...
guess the char: k
k ... hit!
Run Code Online (Sandbox Code Playgroud)