0

我想找到正在执行作为参数给出的某个命令的所有用户的名称。必须使用 grep。我试过:ps aux | grep $1 | cut -d" " -f1,但这不是想要的结果。

4

3 回答 3

0

我猜你正在寻找这个。

# cat test.sh
ps aux | grep $1 | grep -v grep | awk '{print $1}'
# ./test.sh bash
root
root
root
于 2013-03-30T16:11:17.113 回答
0
/usr/ucb/ps aux | awk '/<your_command_as_parameter>/{print $1}'|sort -u

例如:

> /usr/ucb/ps aux | awk '/rlogin/{print $1}' | sort -u
于 2013-03-28T13:33:10.457 回答
0

获取进程信息而不是正在搜索进程的进程有一个技巧,即将名称变成正则表达式。例如,如果您要搜索ls,请将搜索词设为grep '[l]s'。除非您搜索grep自身或单字母命令名称,否则此方法有效。

这是procname我使用的脚本;它适用于大多数 POSIX shell:

#! /bin/ksh
#
#   @(#)$Id: procname.sh,v 1.3 2008/12/16 07:25:10 jleffler Exp $
#
#   List processes with given name, avoiding the search program itself.
#
#   If you ask it to list 'ps', it will list the ps used as part of this
#   script; if you ask it to list 'grep', it will list the grep used as
#   part of this process.  There isn't a sensible way to avoid this.  On
#   the other hand, if you ask it to list httpd, it won't list the grep
#   for httpd.  Beware metacharacters in the first position of the
#   process name.

case "$#" in
1)
    x=$(expr "$1" : '\(.\).*')
    y=$(expr "$1" : '.\(.*\)')
    ps -ef | grep "[$x]$y"
    ;;
*)
    echo "Usage: $0 process" 1>&2
    exit 1
    ;;
esac

bash中,您可以使用变量子串操作来避免以下expr命令:

case "$#" in
1)  ps -ef | grep "[${1:0:1}]${1:1}"
    ;;
*)
    echo "Usage: $0 process" 1>&2
    exit 1
    ;;
esac

这两个都运行ps -efps aux如果您愿意,可以使用。对“命令”名称的搜索不受命令的命令部分的限制,因此您可以使用它procname root来查找由 root 运行的进程。匹配也不限于一个完整的单词;你可以考虑grep -w(一个 GNUgrep扩展)。

这些的输出是来自的全行数据ps;如果您只想要用户(第一个字段),则将输出通过管道传输到awk '{print $1}' | sort -u.

于 2013-03-30T19:03:41.373 回答