If statement in awk

I run my script "switch.sh" repeatedly (within 30 seconds). Each time script is triggered, script itself should kill all previous process.

Here is my code:

for pid in $(ps -fe | grep 'switch.sh' | grep -v grep | awk '{if ($2<$$) print $2}'); do
         sudo kill -9 $pid
done

sleep 30

I can't figure out, why this can't work. The problem is awk '{if ($2<$$) print $2}. If I use numbers instead of $$ then it works, but if I use variables, then if statement doesn't work. I also try with variable instead of $$ but with no luck

Any suggestions?
Thanks.

$$ is special variable of the shell (not of awk ). Shell's variable are not visible inside awk (the way you have used in your code).

You may want to consider

awk -v pid=$$ '{if ($2<pid) print $2}'
1 Like

In addition, I would consider using $2!=pid , since at some point, the numbering of processes may start anew, so an earlier process is not always guaranteed to have a lower number..

1 Like

Here is a simpler way assuming pgrep is available on your OS :

for pid in $(pgrep switch.sh) ; do
    [ $pid != $$ ] && sudo kill $pid
done
sleep 30

Notes:

  • You might need to use "pgrep -f switch.sh" depending on how this script is called.
  • Avoid using "killl -9" unless you have valid reasons (and there are not much of them) to do so

If pkill is avaliable.
First: store your pid.

#!/bin/bash
switch.sh &
echo $! >/path/to/pid.file

Second: if still alive use pkill:

       -P ppid,...
              Only match processes whose parent process ID is listed.

I noticed that, thanks. I also try with !=, but since I would trigger script very fast, even before previous script finish kill process, then somehow previous triggered script can kill next triggered script.

OK, I see what you mean. I guess the best method would be to record the pids of the processes as suggested earlier in this thread and use those to kill the processes.

Do these processes need to govern themselves? Perhaps it would be better to have a parent process who regulates its children and that can be triggered to fire off the next child only after killing any previous child processes first?