top -o %MEM -b > file.txt

time1 = Mar 27 21:27:55

time2 = Mar 28 20:27:32

I need to only redirect the output of the command top -o %MEM -b to output.txt

if time1 <= date1 < =time2

where time1,time2,date1 are the date I choose! I could use Unix time!

Is it possible in linux shell?

How can I do it? I should save the information in XML/JSON format instead of txt file!

  • where does values for time1, time2 and date come from?
    – rsm
    Mar 29 '17 at 16:16
  • @rsm:time1,time2,date1 are the date I choose!
    – Ed S
    Mar 29 '17 at 18:59
  • 1
    ok, so can you choose them in unix time (seconds since 1970-01-01)? it's much easier to work on numbers than on string respresentation of date.
    – rsm
    Mar 31 '17 at 11:45
  • @rsm: yes! I can convert it to unix time!
    – Ed S
    Mar 31 '17 at 18:56
  • to keep things clean here, can you please ask about converting top output to XML/JSON in separate question, and leave this question as it was before?
    – rsm
    Mar 31 '17 at 23:55

Modern shells are programming languages, so you can use arithmetic to check for dates condition. However, top in batch mode runs until the iteration limit is reached, and once you start top, you can't check for dates condition. So you have to run top with iteration limit set to 1 and restart it in while loop:

date1=`date +%s` #we initialize date1 with current unix time

while ((1)); do
    if (($time1 <= $date1 && $date1 <= $time2)); then
        top -o %MEM -b -n 1 >> $output_file
    sleep $iteration_delay
    # something should update date1, time1 or time2 here...?

EDIT: To use this script, copy/paste it to for example mytop.sh file, set executable on it:

chmod +x mytop.sh

and then you can start it as usual, by:


To cancel, press ctrl+c.

There is no visual indicator it's running and some people feel better when there is some output. If you want, you can add for example:

echo .

line in the script after sleep line, to print new dot on every iteration.

  • How can I run this script?
    – Ed S
    Apr 1 '17 at 0:10
  • 1
    @EdS good point, please check my updated answer and let me know if there is something not clear now.
    – rsm
    Apr 1 '17 at 0:21
  • 1
    Thank you! That's clear! I posted another question: superuser.com/questions/1194437/…
    – Ed S
    Apr 1 '17 at 0:35
  • the script does not stop running...
    – Ed S
    Apr 7 '17 at 20:24
  • @EdS use [ctrl] + [c] to stop the script (you might need to press it couple times).
    – rsm
    Apr 8 '17 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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