aherrero aherrero - 4 months ago 21
Bash Question

Shell script: top command and date command at once

I would like to print in a file the % of cpu usage of a process (top command) + the date when this top command gets the information, for each 0.5 seconds (each line with the date + this cpu information)
If I write in a shell script, I would do something like

while [ ! -f $STOP_FILE ]
echo "$(date +%s.%N)" >> $REPORT_FILE
top -b -n 1 -p myProcessPID | grep myProcessName | awk -F " " '{print $12 "\t" $9}' >> result.txt
sleep 0.5

But I can not use the -n 1 option in top to get the cpu information because the first iteration is "from system boot until now" so I need the other iterations.

Therefore, I am looking for some combination of commands to get the process information with top command + a date with nanoseconds (date +%s.%N) (The top command also results a time in the first line in the header, but I want the milliseconds)

I am trying something like,

echo $(date +%s.%N) $(top -d 0.5 -n 100 -p myProcessPID | grep myProcessName) >> results.txt

But the date is only printed the first iteration.

Any ideas?

Sorry if I am not very accurate with the question, I am new with this scripts and writing here..


You can achieve this by piping the output of top through awk, and having awk run date. For example:

top -d 0.5 -n 100 -p myProcessPID \
   | awk '/myProcessName/ { system("date +%s"); print $0 }'

You can exert arbitrary control over the format of the output by adjusting the awk program. Note also that you do not need a separate grep, since awk's internal pattern matching serves perfectly well.