交互式脚本编程:输入读取、循环控制与输入验证
1. 读取键盘输入
在脚本编程中,读取用户的键盘输入是实现交互性的重要环节。read命令是实现这一功能的关键工具,它可以从标准输入读取数据,并将其存储在变量中。
1.1read命令基础
运行以下脚本,展示了read命令的基本用法:
[me@linuxbox ~]$ read-single Enter one or more values > a b c d REPLY = 'a b c d'read命令支持多种选项,例如-p选项可用于提供提示字符串:
#!/bin/bash # read-single: read multiple values into default variable read -p "Enter one or more values > " echo "REPLY = '$REPLY'"而-t和-s选项结合使用,可以实现读取“秘密”输入并设置超时时间:
#!/bin/bash # read-secret: input a secret passph