Bash 选择选项而不按 Enter 键

Bash 选择选项而不按 Enter 键

我有一个这样的脚本:

#!/bin/bash

clear

echo -n "Choose an option:
1) Encrypt
2) Decrypt
3) Quit
-> "

read opzione

if [ "$opzione" == "1" ]; then

echo -n "Drag here the file to encrypt: "
read chiaro
...
fi

我想让脚本在输入数字后自动接受该数字。是否可以?

谢谢

答案1

您可以使用以下-n chars选项:来自help read

  -n nchars return after reading NCHARS characters rather than waiting
        for a newline, but honor a delimiter if fewer than NCHARS
        characters are read before the delimiter

或者,在较新版本的 bash 中,您可以用一条语句替换整个构造select,该语句为您实现选择列表

$ select opzione in "Encrypt" "Decrypt" "Quit"; do echo "You chose $REPLY"; done
1) Encrypt
2) Decrypt
3) Quit
#? 1
You chose 1
#? ^C

相关内容