Bash 脚本:在帐户删除过程中忽略 unix 帐户的删除

Bash scripting : Ignore deletion of unix accounts during account removal process

需要清除 Linux 框上的用户帐户,少数情况除外。为我执行相同操作的脚本是

#UIDMAX will contain the minimum value used by OS for ID selection
UIDMIN=`grep "UID_MIN" /etc/login.defs`

#UIDMAX will contain the mixnimum value used by OS for ID selection
UIDMAX=`grep "UID_MAX" /etc/login.defs`

for i in  awk -F: -v "min=${UIDMIN##UID_MIN}" -v "max=${UIDMAX##UID_MAX}" '{ if (  >= min &&  <=max ) print }' /etc/passwd
do 
     userdel -r $i  
done

但我想添加一些存储在变量中的异常,脚本在删除用户帐户过程中应忽略这些异常。 e.g exceptions="test1 test2 test" 我希望 userdel 在执行上述脚本

期间忽略 exceptions 变量中提到的用户

为什么要使用 awk?

# using lower-case variable names is conventional for things which are neither builtins
# nor environment variables to avoid namespace conflicts.
min=$(grep "^UID_MIN" /etc/login.defs); min=${min##*[[:space:]]}
max=$(grep "^UID_MAX" /etc/login.defs); max=${max##*[[:space:]]}

# set up an associative array of users to ignore
declare -A users_to_ignore=( [test1]=1 [test2]=1 [test]=1 )

while IFS=: read -r name _ pid _ <&3; do
  # check not only for pid min and max, but also presence in users_to_ignore
  if (( pid >= min && pid < max )) && ! [[ ${users_to_ignore[$name]} ]]; then
    userdel -r "$name"
  fi
done 3</etc/passwd

如果您想在使用不同目录源(NIS、LDAP 等)的系统上工作,并且您的操作系统提供 getent,您可以使用 3< <(getent passwd) 而不是 3</etc/passwd;这样更灵活。


如果要支持早于 4.0 的 bash 版本,可以使用:

users_to_ignore="test1 test2 test"

...和...

[[ " $users_to_ignore " =~ " $name " ]]

保持简单,使用 awk 来做它擅长的事情(解析文本)并使用 shell 来做它擅长的事情(对命令的调用排序):

awk -F: -v exceptions="test1 test2 test" '
BEGIN {
    split(exceptions,tmp,/ /)
    for (i in tmp) {
        except[tmp[i]]
    }
}
NR==FNR {
   if ( sub(/UIDMIN/,"") ) min = [=10=]
   if ( sub(/UIDMAX/,"") ) max = [=10=]
   next
}
 >= min &&  <=max && !( in except) {print }
' /etc/login.defs /etc/passwd |
while IFS= read -r name
do 
     userdel -r "$name"  
done

请注意,以上只是我尝试翻译您的命令,因为您没有提供任何示例输入和输出,因此请在执行前自行检查。