我正在创建一个以组名命名的脚本,它应该打印所有用户和他们所在的组,包括给定的用户和组,但我仍然想不出如何正确地这样做,下面是我的代码:
#!/bin/bash
# contentFile is the file you are trying to read
# contentFile will be a parameter supplied by the user
# thus we leave it empty for now
groupName=
## List of options the program will accept;
## those options that take arguments are followed by a colon
## in this case, group name: n
optstring=n:
## The loop calls getopts until there are no more options on the command line
## Each option is stored in $opt, any option arguments are stored in OPTARG
while getopts $optstring opt
do
case $opt in
n) groupName=$OPTARG ;; ## $OPTARG contains the argument to the option (contentFile in this context)
*) exit 1 ;; ## exit if anything else other than -f file name was entered
esac
done
groups=$(cat /etc/group | cut -d: -f1)
for user in $(cat /etc/passwd | cut -d: -f1)
do
echo grep -q $groupName $groups
if [ $? = 0 ]
then
echo "- grupuri:" "$user" "\n;"
fi
done我得到的输出
grep -q root adm wheel kmem tty utmp audio disk input kvm lp optical render storage uucp video users sys mem ftp mail log smmsp proc games lock network floppy scanner power systemd-journal rfkill nobody dbus bin daemon http systemd-journal-remote systemd-network systemd-resolve systemd-timesync systemd-coredump uuidd dnsmasq rpc gdm ntp avahi colord cups flatpak geoclue git nm-openconnect nm-openvpn polkitd rtkit usbmux fsociety postgres locate mongodb dhcpcd docker openvpn mysql预期产出:
whoopsie - grupuri:whoopsie;
colord - grupuri:colord;
sssd - grupuri:sssd;
geoclue - grupuri:geoclue;
pulse - grupuri:audio;pulse;pulse-access;我们非常感谢你的帮助。
发布于 2021-01-28 15:34:02
考虑下面的bash脚本;
group='certuser'
for user in $(awk -F ':' "/${group}/"'{print $4}' /etc/group | tr ',' '\n'); do
echo "$(groups $user)"
done哪里
awk -F ':' '/certuser/ { print $4 }' /etc/group
获取$group ('certuser')组中的每个用户,由,分隔。
使用awk删除组信息,因此我们只保留用户| tr ',' '\n'
将csv发送到for-循环的管道。echo "$(groups $user)"
使用groups命令获取该组中的所有用户发布于 2021-01-28 15:37:58
使用getent命令检索有关组和用户的信息。特别是,getent group查询组,而getent passwd查询用户。
#! /bin/bash
group=$1
gid=$(getent group "$1" | cut -d: -f3)
getent passwd \
| awk -F: -v gid=$gid '($4==gid){print $1}' \
| xargs -n1 groupshttps://stackoverflow.com/questions/65939946
复制相似问题