脚本user.sh:

#!/bin/bash
#Description:create user and password

read -p "Please input username:" user

if [ -z $user ];then
  echo "username is needed."
  exit 2
fi
#使用‐z可以判断一个变量是否为空,如果为空,提示用户必须输入账户名,并退出脚本,退出码为2

stty -echo
#使用 stty ‐echo关闭shell的回显功能,在输入pass时,不会在屏幕显示输入的密码
read -p "Please input password:" pass
stty echo
#使用 stty echo打开shell的回显功能
pass=${pass:-123456}
#如果变量pass没被声明,那么就使用默认值
useradd $user
echo
echo $pass | passwd --stdin $user

脚本验证:

[root@elasticsearch ~]# sh user.sh 
Please input username:aa
Please input password:
Changing password for user aa.
passwd: all authentication tokens updated successfully.
[root@elasticsearch ~]# cat /etc/passwd | grep aa
aa:x:1003:1003::/home/aa:/bin/bash
[root@elasticsearch ~]#