【发布时间】:2021-05-02 12:22:12
【问题描述】:
我正在创建一个带有组名的脚本,它应该打印所有用户和他们所在的组,包括给定的用户,但我仍然不知道如何正确执行,这是我的代码:
#!/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
- grupuri: mysql \n;
预期输出:
whoopsie - grupuri:whoopsie;
colord - grupuri:colord;
sssd - grupuri:sssd;
geoclue - grupuri:geoclue;
pulse - grupuri:audio;pulse;pulse-access;
非常感谢您的帮助
【问题讨论】:
-
什么不起作用?有什么错误吗?
-
你能不能只做 cut -d: -f1 /etc/passwd | xargs 组?
-
感谢您的快速回复。我没有收到错误,但我没有得到我正在寻找的输出或数据。我更新了问题以包含我得到的输出。
-
@RamanSailopal,它只打印“根”组
-
它应该打印在 /etc/passwd 中找到的每个用户的组