【shell脚本练习】判断用户存在和用户类型

来源:互联网 发布:淘宝国际快递转运 编辑:程序博客网 时间:2024/06/06 15:37

题目

写一个脚本
1. 传递一个参数给脚本,此参数为用户名;
2. 如果用户存在,则执行如下任务
* 如果用户的id号小于500,显示其为管理员或系统用户;
* 否则,显示其为普通用户;
3. 如果用户不存在,则添加之;

解答

#!/bin/bashusername=$1if [ "$username" = "" ]; then    echo "please input a username"    exit 1fiif id $username &> /dev/null; then      userid=$(id -u $username)    if [ $userid -lt 500 ];then        echo "$username is a admin user"    else        echo "$username is a normal user"    fielse    useradd $username    if [ $? -eq 0 ]; then  #判断用户是否添加成功        echo "Add user $username."    else        echo "Can not add $username."    fifi

说明

  • id $username &> /dev/null 这里后面的重定向是把无用的输出消除
0 0