LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Print all PID folders from /proc line-by-line with this format (( PID: command-line )) (https://www.linuxquestions.org/questions/linux-newbie-8/print-all-pid-folders-from-proc-line-by-line-with-this-format-pid-command-line-849753/)

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:
Code:

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:
Code:

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

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


colucix 12-12-2010 09:36 AM

Code:

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

courteous 12-12-2010 02:26 PM

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

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

impert 12-12-2010 03:01 PM

Code:

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:
Code:

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)"
done

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:
Code:

for i in /proc/[1-9]*
do
  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.
Code:

${string##substring}

    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 08:36 AM.