Linux – Store the output of date and watch command to a file

command linedatelinuxunixwatch

I am a newbie to linux and I am trying to watch a command and try to log it into a file. I tried

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

and am expecting a result like

TIME: 10:32:30    12
TIME: 10:32:40    18
TIME: 10:32:50    2

to be stored in logfile. However, when the logfile has unprintable characters in in. How do I get this kind of output from the command li

Best Answer

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.

Related Question