Home > Software design >  forming an IP out of two variables
forming an IP out of two variables

Time:03-29

I apologize beforehand if the question is out of place. I'm working on a script that greps the first three octets of an IP address and sends it to a variable. Next I want to use that variable and set a range in a for loop but it's not working.

This is my code;

device_ip=$(ip addr show eth1 | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.')

for i in {191..200};
do
printf device_ip | ping -c 1 "$device_ip""$i"
done

It does everything except for combining the two variables to ping. Output;

sh myscript.sh

ping: unknown host x.x.x.
x.x.x.{191..200}

Can anybody point me in the right direction? Where am I going wrong?

Many thanks in advance,

CodePudding user response:

Can you try this ;

device_ip=$(ip addr show eth1 | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.')

END=200
for ((i=191;i<=END;i  )); 
do
    ping -c1 ${device_ip}${i}
done

CodePudding user response:

This works for me:

for ip in $device_ip.{191..200}; do ping -c 1 $ip; done

Is it possible you aren't using bash?
Check your #! shebang line. If your very first line's very first two characters aren't #! then it's just a comment.

Also,

printf device_ip | ping -c 1 "$device_ip""$i"

Is not going to do what you expect. It's going to print the string "device_ip" onto the STDIN of ping, which isn't coing to read it. Take the printf statement out entirely, it serves no purpose and confuses the code.

Also, while this will work, it's a little visually noisy for no reason. "$device_ip""$i" generates the same output at "$device_ip$i", which is easier to read. Perhaps even better, "${device_ip}${i}". That's all just a style preference, though.

CodePudding user response:

Bash:

#!/bin/bash
device_ip="$(ip -o -4 a sh eth1|grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.'|head -1)" # make sure you get only the first IP, in case eth1 returns more than 1

for i in {191..200}
do
echo pinging IP: ${device_ip}${i}
ping -c1 ${device_ip}${i}
done

CodePudding user response:

Here is a possible solution:

device_ip=($(ip -o address show eth0 | grep -Eo '([0-9]{1,3}\.){3}'))

for address in ${device_ip[0]}{191..200}; do
    ping -c 1 $address
done

And here is an alternative using Bash match operator:

if [[ $(ip -o address show eth0) =~ ([0-9]{1,3}\.){3} ]]; then
    for address in ${BASH_REMATCH}{191..200}; do
        ping -c 1 $address
    done
fi
  • Related