Bash 和用户交互

用read命令和用户交互

方式1:echo -n "enter a name:"; read name

方式2:read -p "enter a name:" uname

方式3:read name(没有提示信息,用户不知道需要用户自己敲键盘了)

方式4:read -t 5 -p "enter a name:" uname 5秒后,用户还没有键入,则超时返回到bash,变量uname则没有值。

# echo -n "enter a name:"; read name
#-n:告诉echo不要换行
enter a name:aaa(aaa是用户键入的)
# read -p "enter a name:" uname
#使用-p选项就不需要和echo组合使用了
enter a name:ddd
[root@localhost ~]# echo $uname
ddd
[root@localhost ~]# echo $name
aaa
[root@localhost ~]# read name
abc(是用户键入的)
[root@localhost ~]# echo $name
abc
[root@localhost ~]# read a b c
11 22 33(是用户键入的)
[root@localhost ~]# echo $a $b $c
11 22 33
[root@localhost ~]# read a b
11 22 33(是用户键入的)
[root@localhost ~]# echo $a $b
#$b的值是22 33
11 22 33
[root@localhost ~]# read a b c
11 22(是用户键入的)
[root@localhost ~]# echo $a $b
11 22
[root@localhost ~]# echo $c
#$c没有值

练习:写一个脚本,创建用户,让用户自己输入用户名和密码,如果用户没有输入或者超时了,则使用默认值

条件id $name &> /dev/null,不要用[]括起来。括起来这个条件判断就被忽略了(就没有被执行)。

#!/bin/bash

read -p "Enter a name:" name
if [ -z "$name" ]; then
    echo "enter a name"
    exit 2
fi

if id $name &> /dev/null; then
    echo "$name exist"
    exit 1
fi

read -p "Enter a passwd for $name:[passwd]" pw
if [ -z "$pw" ]; then
    pw="passwd"
fi

useradd $name
echo $pw | passwd --stdin $name &> /dev/null
echo "add user $name done"

检查bash脚本的语法错误:-n

如果语法有错误,比如少写fi等。

只能检查到语法的错,检查不到命令错误。比如就写个a,是检查不出错误的

# bash -n adduser.sh
adduser.sh: line 26: syntax error: unexpected end of file

调试执行bash:-x

# bash -x adduser.sh
+ read -p 'Enter a name:' name
Enter a name:us1
+ '[' -z us1 ']'
+ id us1
+ echo 'us1 exist'
us1 exist
+ exit 1
# c/c++ 学习互助QQ群:877684253 ![](https://img2018.cnblogs.com/blog/1414315/201811/1414315-20181106214320230-961379709.jpg) # 本人微信:xiaoshitou5854
原文地址:https://www.cnblogs.com/xiaoshiwang/p/12299787.html