Reputation: 33
I need to write a script to enter 2 IP addresses and then change them to binary.
I tried this script but it works just with numbers. I can't write the IP thus: 192.168.1.1
, but when I write it as 100
it's working fine.
#!/bin/bash
echo "Ebter the first ip"
read ip1
echo "Enter the second ip"
read ip2
a=`echo "obase=2;$ip1" | bc`
b=`echo "obase=2;$ip2" | bc`
echo $a
echo $b
What is wrong in my script?
Upvotes: 0
Views: 3078
Reputation: 2201
what you can do:
#!/bin/bash
function convip()
{
CONV=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
ip=""
for byte in `echo ${1} | tr "." " "`; do
ip="${ip}.${CONV[${byte}]}"
done
echo ${ip:1}
}
echo "Enter the first ip"
read ip1
echo "Enter the second ip"
read ip2
a=`convip "${ip1}"`
b=`convip "${ip2}"`
echo "${a}"
echo "${b}"
Result:
Enter the first ip
1.1.1.1
Enter the second ip
2.2.2.2
00000001.00000001.00000001.00000001
00000010.00000010.00000010.00000010
EDIT: updated to keep dots
Upvotes: 1