Logon profile kill script only partially working

I have been having an issue with the new motorola rf scan guns opening up too many sessions at once. It seems they will open a new connection for no reason, leaving the old one in the background and the user has no idea it is happening. To combat this, I have added the following code to the logon profile script that is supposed to see if the user's IP address is already logged on and if it is, it will kill the old session and let the new one on:

IP=$(who am i| awk '{print$6}')
IPCNT=$(who -u | grep $IP |wc -l)                                 
if [$IPCNT -ge 1 ]                                                
then                                                              
who -u | grep $IP |sed -e 's/://g' | awk '{print$6,$7,$8}' > idle 
cat idle | sort -k6 | awk '{print$2}' > idlegood                  
pts=$(who am i|awk '{print$2}')                                   
newpid=$(who -u | grep "$pts " | awk '{print$7}')                 
cat idlegood | grep -v "$newpid" > oldpids                        
while read PID; do kill -9 $PID; done < oldpids                   
fi                                                                

after that part it executes the main program all the users run.

It seems to work but every now and then one of the user accounts that uses this profile script will open up another session anyway.

As you can see, I am a beginner and I am sure there is a much more elegant way to do this, but I am still learning. Can anyone tell me why it could be that it works for most users but not others?

Thanks

Not bad for a beginner. I'm surprised the line with the "if" isn't a problem, however. You need a space between [ and $IPCNT.

Second, it's better to do a kill -1 $PID than kill -9. The former will try to close the child processes of a shell, while the latter may result in hung child processes. Better yet, don't just kill the process, but kill the process group. This is the second field from "ps -j $PID". So you can do:

while read PID; do 
 GPID=$( ps -j $PID | awk 'NR==2 { print $2 }' )
 kill -1 -$GPID
done < oldpids

It might also be necessary to wait for two seconds before continuing the script, giving the system a chance to perform the kills before the script continues. Adding "sleep 1" I think might be enough.

Also, you don't have to do a cat every time -- grep, sed, awk can all take a filename as an argument -- but maybe using cat helps you keep things straight. Also, no need to do a grep and then an awk. Awk does both. (sed -n works similarly.)

My system's "whoami" doesn't work the same as yours, otherwise I could test a similar script. But fix the problem with the bracket