Georgi Georgiev
Georgi Georgiev

Reputation: 1623

Bash shell getting only PID from PS doesn't work

I am using Ubuntu and bash shell.

I can't understand why the following command returns the whole line instead of only PIDs:

$ ps -ef | awk  "{print $2}" | head -3
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 feb18 ?        00:00:32 /sbin/init splash
root         2     0  0 feb18 ?        00:00:00 [kthreadd]

Any suggestions?

Upvotes: 0

Views: 1452

Answers (1)

hek2mgl
hek2mgl

Reputation: 158190

That's a shell quoting issue. If in double quotes, the shell expands the "$2" to an empty string because it is unset. That leaves awk '{print }' which will print the whole line.

Use single quotes to prevent expansion:

ps -ef | awk '{print $2}' | head -3

Btw, you can use the ps command to get the pid, awk isn't required for that:

ps -efho pid

Upvotes: 5

Related Questions