1

I am trying to collect some statistics for a script that I run on a daily bases. I would like to get the amount of time that is actually spent sleeping. Is there a way to just get the sum of all sleep cycles. For example:

#some task
sleep 5
#some task
sleep 2

I want the result to give me 7. This script contains many files with multiple loops and conditions. The solution will need to run with the script to see what sleep is actually being called and how many times.

  • Is it literally a script that has sleep calls in it? – user1794469 Feb 11 '20 at 16:13
  • yes, it is just a huge script with many conditions and loops. – nghj Feb 11 '20 at 18:08
0

A quick and dirty answer would be to just grep for them and add them up with awk:

grep -o 'sleep [0-9]\+' input.sh | awk '{ sum +=$2 } END { print sum }'

This says use grep to search 'input.sh'. On every line print only (-o) the matching part of the line. The match should be the sleep string followed by 1 or more numbers between 0 and 9. So now we have something that will only print out:

sleep 5
sleep 2

We send that list to awk which gets processed line by line and adds all the second columns up. At the end it prints out the total.

NOTE: This is a pretty fragile solution. For example, if you have a commented out line:

# we used to do sleep 1000 here by it was too slow

You will still include that in the total. If you know more about your script to can make a more robust pipeline. For example if you know the sleep calls are always at the beginning of a line you can anchor grep:

grep -o '^sleep [0-9]\+' | ...

Also a script with many sleeps in it is pretty suspect. There are nearly always better ways to organize automation and sleep is mostly only useful for testing.

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.