Kevin
Kevin

Reputation: 2688

Bash Script Get Port Usage

I need to find out if a port is in use in a specific port range.

I am setting up a script to create php-fpm pools, and want to make sure I can check for the next available port that is not in use.

netstat -ntpl | grep [0-9]:${1:-11211} -q ;

Gets me what I need for seeing if that specific port is in use, but how can I do this for a port range? Say... 11211 - 12655

Should I loop a range, and stop at the "found" next available? However, this is returning me 1's for everything.

for i in {11212..12655}
do
    netstat -ntpl | grep [0-9]:${1:-i} -q ;
    echo $i:$?
done

    i=11212;
END=12655;
while [ $i -le $END ]; do
    netstat -ntpl | grep [0-9]:${1:-i} -q ;
    echo $?;
    i=$(($i+1));
done;

Upvotes: 1

Views: 554

Answers (2)

Kevin
Kevin

Reputation: 2688

for i in {11212..12655}
do
    netstat -ntpl | grep [0-9]:${1:-i} -q ;
    echo $i:$?
done

Does exactly what I need.

Upvotes: 1

fedorqui
fedorqui

Reputation: 290415

If you want to compare numbers, grep will make you use regular expressions. And a regex for a range 11211-12655 is going to be a bit boring to type.

What about using awk instead?

netstat -ntpl | awk 'split($4, a, ":")==2 && a[2]>=11211 && a[2]<=12655'

This gets the 4th column of netstat's output and splits its content in two :-separated slices. Then, you have the data in the array a[] to play with and define the range you want it to match.

Upvotes: 3

Related Questions