3

我已经开始编写一小段代码来打印 linux 框中可用的所有用户列表。但是我想将一个一个用户传递到我的命令中,以一起显示每个用户的详细信息。

列出所有用户

root@bt# getent passwd | grep /home/ | cut -d ':' -f 1

root
san
postgres

现在我想将一个用户传递给下面的命令,以一起显示每个用户的详细信息。

root@bt# chage -l ${user1} ; chage -l ${user2} etcc.

我应该在这里使用 for 循环还是 while 循环?任何人都可以帮助我建议如何写相同的吗?

4

2 回答 2

1

您可以使用while循环:

getent passwd | grep /home/ | cut -d ':' -f 1 | \
  while read user ; do
    chage -l "$user"
  done

for循环:

for user in $(getent passwd | grep /home/ | cut -d ':' -f 1) ; do
    chage -l "$user"
done

xargs

getent passwd | grep /home/ | cut -d ':' -f 1 | \
  xargs -n1 chage -l
于 2012-09-30T11:07:39.587 回答
1

我会使用xargs,它在前一个管道的每个输出项上运行一个命令:

getent passwd | grep /home/ | cut -d ':' -f 1 | sudo xargs -I % sh -c '{ echo "User: %"; chage -l %; echo;}'
  • sudo用于获取有关所有用户的信息,如果您无权访问此信息,则可以删除sudo
  • -I % is used to specify that % is a placeholder for the input item (in your case a user)
  • sh -c '{ command1; command2; ...;}' is the command executed by xargs on every % item; in turn, the command sh -c allows multiple shell commands to be executed
  • '{ echo "User: %"; chage -l %; echo;}' echoes the current user in %, then runs chage -l on this user and finished with a final empty echo to format the ouput
于 2012-09-30T11:08:00.170 回答