Search code examples
bashwhile-looppipenetstat

Building a killer script in bash


I've been trying to learn the syntax of logic statements in bash, how to do if/else, pipes and stuff. I'm trying to build a bash script, but I fail miserably after 3 hours of not getting how this stuff works.

Now I need this little script, I'll try to explain it using a generalized code, or call it whatever you want. Here you go:

while variable THRESHOLD = 10

{
if netstat -anltp contains a line with port 25565
then set variable THRESHOLD to 0 and variable PROCNUM to the process number,
else add 1 to variable THRESHOLD
sleep 5 seconds
}
kill the process No. PROCNUM
restart the script

Basically, what it does is, that once the socket closes, after a few tries, it kills the process which was listening on that port.

I'm pretty sure it's possible, but I can't figure out how to do it properly. Mostly because I don't understand pipes and am not really familiar with grep. Thank you for your help, in advance.


Solution

  • Don't want be offensive, but if you can write a "generalized" program all you need is learn th syntax of the while, if for bash and read the man pages of the grep and kill and so on...

    And the pipes are the same as in your garden. Having two things: tap and pond. You can fill your pond with many ways (e.g. with rain). Also, you can open your tap getting water. But if you want fill the pond with the water from a tap, need a pipe. That's all. Syntax:

    tap | pond
    
    • the output from a tap
    • connect with a pipe
    • to the (input) of the pond

    e.g.

    netstat | grep
    
    • the output from a netstat
    • connect with a pipe
    • to the input of the grep

    that's all magic... :)

    About the syntax: You tagged your question as bash.

    So googling for a bash while syntax will show to you, this Beginners Bash guide

    http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_02.html
    

    to, and you can read about the if in the same website.

    Simply can't believe than after 3 hours you cannot understand basic while and if syntax to write your program with a bash syntax - especially, when you able write an "generalized" program...

    is is not to hard (with modifying the 1st example in the above page) to write:

    THRESHOLD="0"
    while [ $THRESHOLD -lt 10 ]
    do
        #do the IF here
        THRESHOLD=$[$THRESHOLD+1]
    done
    

    and so on...