4 ms·
> Quick Infinite Loop I use this a lot for polling type commands: do_every_n_secs "ps -eaf | grep blablabla" 5 function do_every_n_secs (){ cmd=$1
by bostonsre 5y ago
> Quick Infinite Loop
I use this a lot for polling type commands:
do_every_n_secs "ps -eaf | grep blablabla" 5
function do_every_n_secs (){
cmd=$1
secs=$2
if [[ $secs -eq "" ]]; then
secs=10
fi
while true; do
echo "################################################################";
date;
eval $cmd
sleep $secs;
done
}
```
- deleted 5y ago[deleted]
- JNRowe 5y agoIn case you're not aware watch(1) performs basically that task: watch -n 5 "ps -eaf | grep blablabla". It can also highlight changes in the text, break itself out of the loop under conditions, and a few other things. The major difference between your function and watch being that watch will use the alternate screen for output if possible.
- bostonsre 5y agoNope, I was not aware. Neat.
- tomcatfish 5y agoIs there a way to make `watch` do this instead? It always goofs up my output, but it would be cool if you could use it here.
- chasil 5y agoThe grep above will match itself in the output. One way that I have seen to filter it out is grep -v grep, but if you are actually looking for grep processes, then this won't work. The shell can also filter these out. Consider this basic shell function: pps () ( IFS=\| ps -ef | while read a do case $a in *$1*|+([!0-9])) printf %s\\n "$a";; esac done ) This uses a shell pattern instead of a regular expression (shells with more features than POSIX can also use regex). It's actually a dual pattern, either no numbers which match the header, or a match of the pattern specified as the first function argument. The function uses a subshell () instead of command grouping {}. This allows IFS to be manipulated without modifying this setting outside the function, at the cost of a fork. POSIX doesn't support local shell variables; if your shell does (with typeset or local keywords), it will be slightly more efficient. My function would slot into yours, but yours would not work in the Debian default (dash) shell, because the "function" keyword is not defined in POSIX. POSIX approaches are the most important, because you can use them just about everywhere.