I haven't tried any of this, just found the instructions with a Google.
An obvious difference between the command you tried directly, which worked, and the command in the script, which didn't, is the "2" in kill -9 $pid 2>/dev/null. I don't know what purpose, if any, it serves, and maybe you'd be better off without it.