Store the output of date and watch command to a file

This can easily be done using watch too without using any scripts.

watch -t -n 10 "(date '+TIME:%H:%M:%S' ; ps aux | grep "pattern" | wc -l) | tee -a logfile"


In order to do what you are looking for, a simple script (as @Ignacio pointed out) should do the trick:

while true
do
    echo "$(date '+TIME:%H:%M:%S') $(ps aux | grep "pattern" | wc -l)" | tee -a logfile
    sleep 2
done

I use tee instead of >> so that you can see the output on your terminal as well as capture it in your log.


watch is meant for output to a display. If you simply want to run a command every X seconds then you should just use a delay loop for that.

while true ; do somecommand ; sleep 2 ; done