Shell 执行某个命令的所有用户。格雷普
我想查找执行作为参数给定的特定命令的所有用户的名称。 必须使用grep。Shell 执行某个命令的所有用户。格雷普,shell,grep,Shell,Grep,我想查找执行作为参数给定的特定命令的所有用户的名称。 必须使用grep。 我尝试过:ps aux | grep$1 | cut-d”“-f1,但这不是理想的结果。我想你正在寻找这个 /usr/ucb/ps aux | awk '/<your_command_as_parameter>/{print $1}'|sort -u # cat test.sh ps aux | grep $1 | grep -v grep | awk '{print $1}' # ./test.sh bas
我尝试过:ps aux | grep$1 | cut-d”“-f1,但这不是理想的结果。我想你正在寻找这个
/usr/ucb/ps aux | awk '/<your_command_as_parameter>/{print $1}'|sort -u
# cat test.sh
ps aux | grep $1 | grep -v grep | awk '{print $1}'
# ./test.sh bash
root
root
root
有一个技巧可以获取进程的信息,而不是搜索进程的进程,这就是将名称转换为正则表达式。例如,如果您正在搜索
ls
,请将搜索词设置为grep'[l]s'
。除非您正在搜索grep
本身,或者搜索单个字母的命令名,否则此选项有效
这是我使用的procname
脚本;它适用于大多数POSIX外壳:
#! /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-ef;如果愿意,您可以使用ps aux。“命令”名称的搜索不限于命令的命令部分,因此您可以使用
(GNU<代码> GRP扩展)。< /P>查找由root运行的进程。匹配也不限于一个完整的单词;您可以考虑<代码> GRP-Wprocname root
这些数据的输出是来自的整行数据;如果您只需要用户(第一个字段),那么将输出通过管道传输到ps
@sarathi它还包括执行/usr/ucb/ps aux | awk'/{print$1}sort-u的用户,但他没有执行作为参数给出的命令。除非您正在寻找运行awk'{print$1}'| sort-u
。grep
case "$#" in 1) ps -ef | grep "[${1:0:1}]${1:1}" ;; *) echo "Usage: $0 process" 1>&2 exit 1 ;; esac