For next available tap device, you can use following function:
function nextTapDevice() { counter=-1 while [ $? -eq 0 ]; do counter=$(($counter+1)) ip link show tap$counter &> /dev/null done echo tap$counter } nextTapDevice
It runs on same principle as @stony described, but it keeps running till ip link show throws an error. Which means no device named tap$counter is available. That device name will be next available device name.
For next available IP range, you first need to adhere to policy or IP range. Make sure this IP range does not collides with other application such as of Docker or so.
For my use case, I have decided to use 172.16.0.0/16. I'll be allocating last octet to each VM (application I am working with). I can run 256 VMs.
I am going to reuse modified version of my nextTapDevice function written above. Instead of returning tap$counter in above function, I'm going to return just the counter.
Here is the rest of the code:
function nextTapDevice() { counter=-1 while [ $? -eq 0 ]; do counter=$(($counter+1)) ip link show tap$counter &> /dev/null done echo $counter } # nextTapDevice function nextIPRange() { for ((i=0; i<$(nextTapDevice);++i)); do output=$(ip -br addr show tap$i | awk '{print $3}') done echo $output | awk -F. '{ print $1"."$2"."$3+1"."$4 }' } nextIPRange
Drawback: The 3rd octet would keep incrementing even after 256. You might want to implement additional checks if your use case exceeds that point.