【发布时间】:2020-03-05 14:16:20
【问题描述】:
我编写了以下脚本来从单词列表中删除用户。词表有 3 或 4 个字段,分别是名字、中间名、姓氏和用户 ID。我正在使用 awk 创建一个用户名,其中包含用户的名字首字母、姓氏和他们 ID 的最后两位数字。然后使用带有标志 r 的命令 userdel 来删除用户的主目录。
但是,当我运行脚本时,它给了我一个错误提示:
Usage: userdel [options] LOGIN
Options:
-f, --force force some actions that would fail otherwise
e.g. removal of user still logged in
or files, even if not owned by the user
-h, --help display this help message and exit
-r, --remove remove home directory and mail spool
-R, --root CHROOT_DIR directory to chroot into
-Z, --selinux-user remove any SELinux user mapping for the user
脚本:
#! /bin/bash
# Removing users using positional parameters
getusername(){
line=${1}
len=`echo ${line}|awk '{ FS = " " } ; { print NF}'`
if [[ ${len} -eq 3 ]]
then
initial=`echo ${line}| awk {'print $1'} |cut -c1`
lastname=`echo ${line} | awk {'print $2'}`
id=`echo ${line}| awk {'print $3'}|grep -o '..$'`
username=`echo ${initial}${lastname}${id} |tr '[:upper:]' '[:lower:]'`
elif [[ ${len} -eq 4 ]]
then
initial=`echo ${line} | awk {'print $1'} |cut -c1`
lastname=`echo ${line} | awk {'print $3'}`
id=`echo ${line}| awk {'print $4'}|grep -o '..$'`
username=`echo ${initial}${lastname}${id} |tr '[:upper:]' '[:lower:]'`
else
echo "Line ${line} is not expected as it should be considered for creating Username and Password"
fi
}
sudo userdel -r $getusername
【问题讨论】:
-
没有像
getusername这样的变量,所以$getusername扩展为空。 -
您可以通过依赖
awk来执行cut或grep -o可以执行的任何操作来减少您的getusername函数启动的进程数。即initial=`echo ${line}| awk '{print substr($1,1,1)'}`和d=`echo ${line}| awk '{print substr($4, length($4)-1)}'`。并且您可以使用line="${1}";len="$(#line}"更轻松地获得len,这当然是多余的,因为您可以测试if [ "${#1}" -eq 3 ] ; ....,它仍然可以自我记录。代码越少,中断的地方就越少;-)!祝你好运。
标签: linux bash shell centos7 userdel