Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have to create list of PID's of the running processes.

Here is the script

ps
echo "fields are "
ps | cut -d' ' -f1

ps is showing

  PID TTY          TIME CMD
 2168 pts/4    00:00:00 sh
 2177 pts/4    00:00:00 mailx
 5191 pts/4    00:00:00 sh
 6494 pts/4    00:00:00 sh
 6495 pts/4    00:00:00 ps
12154 pts/4    00:00:00 sh
12172 pts/4    00:00:00 mailx
15618 pts/4    00:00:00 bash

But the output of cut pipeline is just

12154
12172
15618
share|improve this question

3 Answers 3

The problem is that cut uses a single space character as a delimiter, but as the column name and the 4 digit PIDs are right aligned there are multiple leading spaces which cause cut to output an empty line.

An alternative approach is to use awk, which copes better with this kind of input:

ps | awk '{ print $1 }'

In the case of ps in particular mindthemonkey's answer is a better approach.

share|improve this answer

For the full list:

ps -eo pid

Or just your processes:

ps -o pid
share|improve this answer

As a third choice, you could also use grep:

ps | grep -oP '^\s*\d+'

The -P enables Perl regular expressions (for the \s,\d and +) and the -o causes grep to print only the matched section pf matching lines.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.