shell脚本基础(六)
bash脚本编程之与用户交互
脚本参数:脚本传递数
用户交互:通过键盘输入数据,从而完成变量赋值操作
read变量赋值
[root@Centos-7-24 opt]# read name
tom
[root@Centos-7-24 opt]# echo $name
tom
-p prompt 给个提示符
[root@Centos-7-24 opt]# echo -n "Enter a username"; read name
Enter a username tom
[root@Centos-7-24 opt]# echo $name
tom
[root@Centos-7-24 opt]# read -p "Enter a username:" name
Enter a username:tom
[root@Centos-7-24 opt]# echo $name
tom
-t timeout 指定时间内未输入将超时退出,变量赋值为空
[root@Centos-7-24 opt]# [ -z "$name" ] && name="obama" --变量name为空时赋值obama
[root@Centos-7-24 opt]# echo $name
tom
[root@Centos-7-24 opt]# read -t 5 -p "Enter a username:" name 5秒之后将超时
Enter a username:tom
[root@Centos-7-24 opt]# [ -z "$name" ] && name="obama"
[root@Centos-7-24 opt]# echo $name
tom
例:
#!/bin/bash
#
read -p "Enter a username:" name
[ -z $name ] && echo "a username is needed!!!" && exit 2
read -p "Enter a passwd for $name,[password]:" passwd
[ -z $passwd ] && passwd="password"
if
id $name &>/dev/null
then
echo "$name is exists!!!"
else
useradd $name
echo "$passwd" |passwd $name --stdin
echo "Add user $name is finished."
fi
bash -n 检查脚本语法错误
bash -x 显示脚本执行过程中错误的地方
浙公网安备 33010602011771号