-   Linux - Newbie (
-   -   Print all PID folders from /proc line-by-line with this format (( PID: command-line )) (

courteous 12-12-2010 09:25 AM

Print all PID folders from /proc line-by-line with this format (( PID: command-line ))
How do you extract all numeric folders from PIDs variable, which is defined as:

PIDs="$(ls -v /proc/)"  # -v for numeric sort
I would like to print all PID (ie. numeric) folders from /proc folder. This does not work:

numberOfPIDs="$(ls /proc/ | wc -l)"

for ((x=0; x < $numberOfPIDs; x++)); do
        echo "$PIDsource | cut -d' ' -f$x"

colucix 12-12-2010 09:36 AM


ls -dv [1-9]*
lists all the PID directories under /proc numerically sorted.

courteous 12-12-2010 02:26 PM

How can I use your snippet outside /proc folder? Why this doesn't work:

ls -dv [1-9]* /proc/

impert 12-12-2010 03:01 PM


ls -dv /proc/[1-9]*

courteous 12-12-2010 03:09 PM

This for loop is much better, but it still gives plenty of errors:

PIDlist="$(ls -dv /proc/[1-9]* | cut -d '/' -f3)" # I need only PIDs
PIDnumber="$(ls /proc/ | wc -l)"

for i in "$PIDlist"; do
        printf "%4u | %10s\n" "$i" "$(cat /proc/$i/cmdline)"

Error example: cat: 4: No such file or directory. Indeed, in terminal cat /proc/4/cmdline returns nothing.

colucix 12-12-2010 04:27 PM

Keep it simple. You might loop over the /proc/PID directories and use parameter substitution or the basename command to retrieve PID. Example:

for i in /proc/[1-9]*
  command="$(cat $i/cmdline)"
  command=${command:-<not available>}        # if command is not set or empty use default
  printf "%5d | %s\n" ${i##*/} "$command"    # ${i##*/} is the same as $(basename $i)
done | sort -k1n

Hope this helps.

courteous 12-12-2010 04:36 PM

What do hash-hash-star-slash, that is ${i##*/}, in printf do? :)

EDIT: Oh, I'm sorry, now I see it in comment. Forward to man basename! :study:

Thank you again.

colucix 12-12-2010 04:47 PM

Actually it is substring removal. Look at the advanced bash scripting guide, here.


    Deletes longest match of $substring from front of $string.

In this case it deletes the longest match of any string * followed by a slash, acting as the basename command.

All times are GMT -5. The time now is 05:48 AM.