Reputation: 133
I'm trying to make a script to see if the process chromium is running. The script should check every 10 seconds if the process is running and it must end when it finds it 10 times. Here is my code.
#!/bin/bash
count=0
while true; do
sleep 10s
isthere=`$(top) | grep -w chromium`
if [ $isthere -ne 0 ]; then
count=$((count+1))
fi
if [ $count -eq 10 ]; then
echo "You found the process 10 times"
exit 50
fi
done
I'm having no output whatsoever. I don't know if I'm using the command top
properly.
Upvotes: 0
Views: 2273
Reputation: 15613
Please use pgrep
.
$ if pgrep ksh >/dev/null; then echo "ksh is running"; fi
ksh is running
In a loop:
i=0
while (( i < 10 )); do
if pgrep ksh >/dev/null; then
(( ++i ))
fi
sleep 10
done
Substitute ksh
with the tool of your choice.
Upvotes: 0
Reputation: 17483
Yep, your usage of top
command is incorrect. You try to invoke it from the shell script and it hangs as a result.
You should use top
command with some specific options. I suggest you use it with -b
option which corresponds to the "batch" mode and -n
options which is for the number of iterations top
produces its output. For more information check man top
.
Also the test for isthere
variable should be amended (we check it for non-emptyness).
The resulting script which works is something like this:
#!/bin/bash
count=0
while true; do
sleep 10s
isthere=`top -b -n 1 | grep -w chromium`
if [ -n $isthere ]; then
count=$((count+1))
fi
if [ $count -eq 10 ]; then
echo "You found the process 10 times"
exit 50
fi
done
Upvotes: 1