如何在`ps aux`命令中始终截取PID?

36

我希望从我的进程中获取pid。 我执行ps aux | cut -d ' ' -f 2,但我注意到有时它会获取pid,有时则不会:

[user@ip ~]$ ps aux 
user  2049  0.5 10.4 6059216 1623520 ?     Sl   date   8:48 process 
user 12290  0.3  6.9 5881568 1086244 ?     Sl   date  2:30 
[user@ip ~]$ ps aux | cut -d ' ' -f 2 

12290
[user@ip ~]$ ps aux |  cut -d ' ' -f 3
2049

请注意,第一个cut命令将其导向2,而第二个命令将其导向3。如何在不必知道使用哪个号码(23)的情况下选出PID?

可以有人告诉我这两者之间的区别,以及为什么它会挑选其中一个而不是另一个吗?

4个回答

67

-d ' '表示使用单个空格作为分隔符。由于2049之前有1个空格,12290之前有2个空格,因此您的命令通过-f 2-f 3获取它们。

我建议使用ps aux | awk '{print $2}'来获取这些进程ID。

或者您可以先使用tr压缩这些空格,然后使用ps aux | tr -s ' ' | cut -d ' ' -f 2


11

您可以随时使用pgrep获取进程的PID。

例如,使用PS AUX获取PID。

wix@wsys:~$ ps aux | grep sshd
root      1101  0.0  0.0  72304  3188 ?        Ss   Oct14   0:00 /usr/sbin/sshd -D
root      6372  0.0  0.1 105692  7064 ?        Ss   06:01   0:00 sshd: wix [priv]
wix       6481  0.0  0.1 107988  5748 ?        S    06:01   0:00 sshd: wix@pts/1
root      6497  0.0  0.1 105692  7092 ?        Ss   06:01   0:00 sshd: wix [priv]
wix       6580  0.0  0.1 107988  5484 ?        S    06:01   0:00 sshd: wix@pts/2
wix       6726  0.0  0.0  13136  1044 pts/1    S+   06:12   0:00 grep --color=auto sshd

现在只需使用pgrep获取PID即可

wix@wsys:~$ pgrep sshd
1101
6372
6481
6497
6580
wix@wsys:~$ 

1
这与原帖的问题有何关联? - Nicolas Melay
2
我认为目标是获取PID,为什么不使用手头的工具而不是使用复杂的命令链。 - Waqar Afridi
如何针对 /sbin/lvmetad -f 执行操作,使得 pgrep 命令无法显示 PID。 - Kishore
"pgrep --full" 对我非常有用。我正在寻找特定的Python脚本调用,而普通的pgrep并不能胜任。 - matt
pgrep并不总是显示进程,你可能需要使用-f参数。 - undefined
显示剩余2条评论

7
您可以使用选项-o仅打印PID:
ps -u user -o pid

1
对于所有的进程,上述的答案都是不错的(例如,使用awk),但对于一些特定的程序进程,我正在采取不同的方法。
你可以尝试使用ps aux | grep <程序名称> | awk '{print $2}',但你会得到两个答案... 以下是一个示例(以及一些调试信息):
$ ps aux | grep gnome-terminal  | awk '{print $2}'
9679
93820
$ ps aux | grep gnome-terminal  | awk '{print $2 " --> " $11 " " $12 " " $13}'  # just debug
9679 --> /usr/libexec/gnome-terminal-server  
93986 --> grep --color=auto gnome-terminal

所以,相反地,可以使用pgrep -f <program-name>,并且grep PID本身不会出现... 示例(再次,有点调试):
$ pgrep -f gnome-terminal
9679
$ pgrep -f -l gnome-terminal  # just debug
9679 gnome-terminal-

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接