1

I have several services running and a bash script that displays their current state using top e.g.

top -b -n1 -p `pgrep -f "proc1|proc2|proc3|proc4|proc5" | 
tr '\n' ',' |               # replace the newlines in the pid list with commas
sed 's/,$//g'` |            # remove the trailing comma and submit to top
grep -vx '.*sed' |          # From the top output: remove the entry for sed
sed 1,6d |                  # and remove the first 6 lines of top

produces

   PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
    660 user1     20   0 5800588 658868  39384 S   0.0   4.3   0:47.72 proc1
    718 user1     20   0 2089772  41068  25032 S   0.0   0.3   0:00.82 proc2
    722 user1     20   0 1046316  34172  25000 S   0.0   0.2   0:02.85 proc3
    725 user1     20   0  833716  23376  18404 S   0.0   0.2   0:00.21 proc4
    729 user1     20   0 2369604 108084  34292 S   0.0   0.7   0:02.76 proc5

Next I would like to take each pid, pass it into 'ps -p <pid> -o start' and insert the output to the corresponding line to produce:

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+   STARTED COMMAND
    660 user1     20   0 5800588 658868  39384 S   0.0   4.3   0:47.72  08:56:23 proc1
    718 user1     20   0 2089772  41068  25032 S   0.0   0.3   0:00.82  08:56:24 proc2
    722 user1     20   0 1046316  34172  25000 S   0.0   0.2   0:02.85  10:27:41 proc3
    725 user1     20   0  833716  23376  18404 S   0.0   0.2   0:00.21  08:56:27 proc4
    729 user1     20   0 2369604 108084  34292 S   0.0   0.7   0:02.76  08:56:29 proc5

I know I can extract the pid using awk but how do I merge/insert the output?

1 Answer 1

0

I figured it out. I also found the -d switch for pgrep which avoids the need to replace newlines with commas.

    echo "    PID USER      VIRT      RES      SHR  %CPU  %MEM     TIME+  START COMMAND"
    top -b -n1 -p `pgrep -d , -f "proc1|proc2|proc3|proc4|proc5"` | 
    sed 1,7d |                                      # and remove the first 6 lines of top
    awk 'BEGIN { OFS="\t" } { command=sprintf("ps -o stime= %s", $1);  command | getline time; close(command); 
        printf("%7s %-10s %8s %8s %8s %5s %5s %9s %6s %s\n", $1, $2, $5, $6, $7, $9, $10, $11 , time, $12) }'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .