makansij
makansij

Reputation: 9865

How to always cut the PID from `ps aux` command?

I'd like to get the pid from my processes. I do ps aux | cut -d ' ' -f 2 but I notice that sometimes it gets the pid and sometimes it does not:

[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

notice that the first cut command is piping it to 2 whereas the second one is piping it to 3. How do I pick out the PID from these without having to know which number to use (2 or 3)?

Can someone please tell me the difference between these and why it picks up one and not the other?

Upvotes: 42

Views: 52316

Answers (4)

For all the processes, the above answers are good (awk one, for example), but for some specific program processes, I am doing something differently.

You can potentially do: ps aux | grep <program-name> | awk '{print $2}', but you would get 2 answers... Example (and a bit of debug):

$ 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

So, instead, pgrep -f <program-name> can be used, and the grep PID itself will not appear... Example (and, again, a bit of debug):

$ pgrep -f gnome-terminal
9679
$ pgrep -f -l gnome-terminal  # just debug
9679 gnome-terminal-

Upvotes: 4

Waqar Afridi
Waqar Afridi

Reputation: 137

You can always use pgrep to get process's PID

E.g PIDs with PS AUX

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

Now just pgrep to get PIDs

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

Upvotes: 11

Minh Tuan Nguyen
Minh Tuan Nguyen

Reputation: 1054

You can use the option -o to print only the pid:

ps -u user -o pid

Upvotes: 8

CtheSky
CtheSky

Reputation: 2624

-d ' ' means using a single space as delimiter. Since there're 1 space before 2049 and 2 spaces before 12290, your command get them by -f 2 and -f 3.

I recommend using ps aux | awk '{print $2}' to get those pids.

Or you can use tr to squeeze those spaces first ps aux | tr -s ' ' | cut -d ' ' -f 2

Upvotes: 76

Related Questions