Search code examples
linuxbashgrepquoteswatch

How to get watch to run a bash script with quotes


I'm trying to have a lightweight memory profiler for the matlab jobs that are run on my machine. There is either one or zero matlab job instance, but its process id changes frequently (since it is actually called by another script).

So here is the bash script that I put together to log memory usage:

#!/bin/bash
pid=`ps aux | grep '[M]ATLAB' | awk '{print $2}'`
if [[ -n $pid ]]
then
    \grep VmSize /proc/$pid/status
else
    echo "no pid"
fi

when I run this script in bash like this:

./script.sh

it works fine, giving me the following result:

VmSize:  1289004 kB

which is exactly what I want.

Now, I want to run this periodically. So I run it with watch, like this:

watch ./script.sh

But in this case I only receive:

no pid

Please note that I know the matlab job is still running, because I can see it with the same pid on top, and besides, I know each matlab job take several hours to finish.

I'm pretty sure that something is wrong with the quotes I have when setting pid. I just can't figure out how to fix it. Anyone knows what I'm doing wrong?

PS. In the man page of watch, it says that commands are executed by sh -c. I did run my script like sh -c ./script and it works just fine, but watch doesn't.


Solution

  • This

    pid=`ps aux | grep '[M]ATLAB' | awk '{print $2}'`
    

    could be changed to:

    pid=$(pidof MATLAB)