Reputation: 11
I'm trying to make a script in bash to ping to addresses at once. The adressess are always 1 over the one the user keyed in.
Example: What is the ip? 192.168.0.10
The program should ping 192.168.0.10 and 192.168.0.11. Finally it should give ping output.
I have problems incrementing on the last digit of the ip. My code:
#!/bin/bash
# Script for å pinge to lokasjoner samtidig.
read input
echo $input
ip1=$input
let "ip2=$input+1"
echo $ip1
echo $ip2
As you can see, I have a long way to go. But my first question is how to increment only the last digits of the input.
Upvotes: 0
Views: 1509
Reputation: 12887
Awk alternative:
ip="192.168.0.10"
ip2=$(awk -F\. '{ print $1"."$2"."$3"."$4+1 }' <<< $ip )
echo $ip2
192.168.0.11
Read the original ip address into awk and separate fields with "." Add 1 to the last field and then set this into the variable ip2
Upvotes: 0
Reputation: 92854
You need to process your ip1
octets separately:
part1=${ip1%.*}"." # first 3 octets (with trailing separator `.`)
part2=${ip1##*.} # last octet
ip2=$part1$[$part2+1]
printf "%s\n%s\n" $ip1 $ip2
The exemplary output:
192.168.0.10
192.168.0.11
Upvotes: 0
Reputation: 19315
using variable expansion and arithmetic expansion
ip2=${ip1%.*}.$((${ip1##*.}+1))
${ip1%.*}
removes the shortest suffix .* (last number)${ip1##*.}
removes the largest prefix *. (all except last number)Upvotes: 4