Skip to content

read

命令结构

sh
read -p "提示文本" 变量名
  • read:Shell 内置命令,用于从标准输入(键盘)读取用户输入。
  • -p:选项(prompt),指定要在输入前显示的提示信息。

扩展用法

(1) 超时自动选择

若用户未在指定时间内输入,自动选择默认值:

sh
read -t 10 -p "Enter your choice (10秒超时): " DBSelect
DBSelect=${DBSelect:-2}  # 超时或空输入时设为 2

(2) 隐藏输入内容(密码场景)

shell
read -s -p "Enter password: " password  # -s 隐藏输入

(3) 多变量输入

sh
read -p "Enter IP and Port (格式: IP Port): " ip port

示例:

sh
while true; do
    read -p "Enter your choice (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 or 0): " DBSelect
    if [[ "$DBSelect" =~ ^[0-9]+$ ]] && [ "$DBSelect" -le 11 ]; then
        break  # 输入合法,退出循环
    else
        echo "错误:请输入 0-11 的数字!"
    fi
done