Shell获取用户输入
基本语法
read [-p prompt] [variable1 variable2...]
-p:输出提示信息
-t:超时时间
-s:隐藏读取,不显示用户输入内容
例子
#! /bin/bash
read -p "Enter your name, please: " username
read -p "Enter your email, please: " email
read -p "Are you sure to continue? [y/n] " input
case $input in
[yY]*)
echo "Your name is $username"
echo "Your email is $email"
;;
[nN]*)
exit
;;
*)
echo "Just enter y or n, please."
exit
;;
esac
效果
例子
#! /bin/bash
password=''
echo -n "Enter password: "
# 使用 while 循环隐式地从标准输入每次读取一个字符,且反斜杠不做转义字符处理
# 然后将读取的字符赋值给变量 char
while IFS= read -r -s -n1 char
do
# 如果读入的字符为空,则退出 while 循环
if [ -z $char ]
then
echo
break
fi
# 如果输入的是退格或删除键,则移除一个字符
if [[ $char == $'\x08' || $char == $'\x7f' ]]
then
[[ -n $password ]] && password=${password:0:${#password}-1}
printf '\b \b'
else
password+=$char
printf '*'
fi
done
echo "Password is: $password"