linux - 使用 unix 编写脚本以获取用户运行的进程

标签 linux bash unix

<分区>

如果我发现我现在有两个用户(UserA 和 UserB)登录到系统,我如何找出这两个用户运行的进程。但是,这里的诀窍是脚本将在无人值守的批处理中运行,无需任何键盘输入。除了被调用。

我知道脚本的第一部分是 谁 | awk '{print $1}' 这个的输出将是 用户A 用户B

我想知道的是,我如何使用此输出并使用一些 ps 命令自动推送它并获得所需的结果。

最佳答案

借助其他答案(更新,以防没有用户登录 - 查看评论),我终于找到了我正在搜索的单行代码。

ps -fU "`who | cut -d' ' -f1 | uniq | xargs echo`" 2> /dev/null

反引号内的内容被执行并“插入到位”。它的工作原理如下:

who             : you know what that does
cut -d' '       : split strings into fields, using ' ' as separator
-f1             : and return only field 1
uniq            : return only unique entries
xargs echo      : take each of the values piped in, and send them through echo: this strips the \n
2> /dev/null    : if there are any error messages (sent to 2: stderr)
                : redirect those to /dev/null - i.e. "dump them, never to be seen again"

所有的输出是

user1 user2 user3

...不管有多少。然后您使用 -fU 标志调用 ps,以完整格式请求这些用户的所有进程(您当然可以更改这些标志以获得您想要的格式,只是将 -U 放在 "` `"中的东西之前

ps -fU user1 user2 user3

关于linux - 使用 unix 编写脚本以获取用户运行的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20006121/

相关文章:

python - 安排Python程序在给定时间段内休眠

c - Unix 信号量问题

c++ - 如何在 Linux 中从其源代码安装 libavcodec 和 libavutil

linux - 如何识别 linux block 设备的请求队列

python - 使用 Python 将复杂参数解析为 shell 脚本

bash - 打印包依赖树

mysql - bash mysql 插入单引号

shell - 在服务器上作为后台进程运行 java jar 文件

c - Linux 下 C 语言的全屏操作

c - 我只想在我的 C 程序中使用 iptables 命令