Bash/xargs:如何批量分配用户权限? [英] Bash/xargs: How to mass assign user privileges?

查看:30
本文介绍了Bash/xargs:如何批量分配用户权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新用户.我当前的用户显然拥有以下权限:

$ 组max adm cdrom sudo dip plugdev lpadmin lxd sambashare

其中 max 是当前用户帐户的名称.

我尝试了参数扩展,但 ${groups} 的输出是空的,所以我只是将组通过管道传输到 xargs

$ 组 |xargs -I _ sudo usermod -aG _ new_user_name

我收到错误消息,说没有文件夹 max adm cdrom sudo dip plugdev lpadmin lxd sambashare 因为很明显 groups 的输出没有被空格分割.>

但正如我所说的 ${groups} 是空的,所以我无法通过管道传输到 xargs.

第二次尝试:

my_arr=(adm cdrom sudo dip plugdev lpadmin lxd sambashare)$ echo ${my_arr[@]} |xargs -I _ usermod -aG _ new_user_name

即使我将参数扩展放在双引号中,数组的参数也不会被拆分.

xargs 仍将管道参数视为一个大字符串 adm cdrom sudo dip plugdev lpadmin lxd sambashare

正确的解决方案是什么?

解决方案

usermod 一次将一个或多个用户添加到一个组,因此您必须使用循环:

for g in "${my_arr[@]}";做usermod -aG "$g";新用户名完毕

请注意,xargs 默认情况下在提供的命令的一次调用中使用尽可能多的参数,因此如果您使用 xargs,请将消耗的参数数量限制为一次一个 (-n 1):

echo "${my_arr[@]}";|xargs -n 1 -I _ usermod -aG _ new_user_name

I have created a new user. My current user obviously has the following rights:

$ groups
max adm cdrom sudo dip plugdev lpadmin lxd sambashare

Where max is the name of the current user account.

I tried paramer expansion but the output of ${groups} is empty, so I just piped groups to xargs

$ groups | xargs -I _ sudo usermod -aG _ new_user_name

I get the error message that there is no folder max adm cdrom sudo dip plugdev lpadmin lxd sambashare because obviously the output of groups is not splitted by whitespace.

But as I said ${groups} is empty, so there is nothing I could pipe to xargs.

Second try:

my_arr=(adm cdrom sudo dip plugdev lpadmin lxd sambashare)

$ echo ${my_arr[@]} | xargs -I _ usermod -aG _ new_user_name

The arguments of the array don't get splitted even though I don't put the parameter expansion in double quotes.

xargs treats the piped arguments still as one big string adm cdrom sudo dip plugdev lpadmin lxd sambashare

What's the right solution?

解决方案

usermod adds one or more users to one group at a time, so you'll have to use a loop:

for g in "${my_arr[@]}"; do
  usermod -aG "$g" new_user_name
done

Note that xargs by default uses as many arguments as possible in one invocation of the supplied command, so if you go with xargs, limit the number of arguments consumed to one at a time (-n 1):

echo "${my_arr[@]}" | xargs -n 1 -I _ usermod -aG _ new_user_name

这篇关于Bash/xargs:如何批量分配用户权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆