-1

I have written an executable shell script which is meant to close the epiphany browser on my raspberry pi if the browser usage is 0. If i run the following command i see values above 0 if the browser in use and if its not then its 0:

top -b -n 1 | grep epiphany-browse | awk '{ totuse = totuse + $9 } END { print totuse }'

but then put it in a script it does not kill the browser process:

while true

sleep 60s

do

if [ top -b -n 1 | grep epiphany-browse | awk '{ totuse = totuse + $9 } END { print totuse }' -eq 0 ]

then

killall epiphany-browser

fi

done
  • Replace your killall with `echo We should kill the browser now`. Do you ever see that message in your shell? – RedX Sep 10 '15 at 15:57
  • 1
    I'm struggling to imagine what the relevance of 0% CPU usage is. Are you trying to shutdown the browser when you're not using it? How does this fit in with preserving everything else running on the device? Why not just set your window manager to run a screensaver on idle and replace/wrap the screensaver with something that kills the process? – symcbean Sep 10 '15 at 16:22

2 Answers2

2

Try with surrounding $(...)

if [ $(top -b -n 1 | grep epiphany-browse | awk '{ totuse = totuse + $9 } END { print totuse }') -eq 0 ]; then ...
Manuel Barbe
  • 2,104
  • 16
  • 21
  • Thank you, that worked. Very odd however because i did exactly the same thing before but it didn't work. I copied and pasted this one, the only thing that was different maybe some spaces. Cheers. – butYouDontLookLikeADeveloper Sep 10 '15 at 16:20
1

Your script is probably calculated into the totuse and so it's never quite zero.

This is an ancient FAQ; the solution is to use a regex which does not match itself.

You might also want to fix the useless use of grep | awk; I am also tempted to rewrite the Awk script to directly exit with true or false so it can be used directly from if, although that complicates the Awk part slightly.

if top -b 1 | awk '/[e]piphany-browse/{ totuse += $9 }
        END { exit 1-(totuse==0) }'; then
    killall epiphany-browser
fi
tripleee
  • 175,061
  • 34
  • 275
  • 318