Alaa Yalda
Alaa Yalda

Reputation: 51

script to Change ip address format,

I'm trying to write a bash script that convert any IP address from CIDR to quad-style.

for example

192.168.1.1/24 ===>192.168.1.1 255.255.255.0

I tried to write this

#!/bin/bash
echo "enter you ip"
read ip
b=`echo $ip | cut -d/ -f1`
a=`echo $ip | cut -d/ -f2`

if a=24 ; then
echo "$b 255.255.255.0"
fi
if a=25; then
echo "$b 255.255.255.128"
fi

I'm getting this output:

1.1.1.1 255.255.255.0
1.1.1.1 255.255.255.128  

when I'm entering /24 or /25 even /26 that I didn't wrote in if condition, I'm getting same output, what is wrong in my script?

Upvotes: 1

Views: 490

Answers (4)

Jahid
Jahid

Reputation: 22438

What if a=24 ; then does is to check if the assignment a=24 was successful or not. Obviously enough, it's always successful (:D), i.e the if block is always passing the test.

In Bash you can do:

if ((a==24));then

Or if you want to be portable, use David Rosa's method:

if [ $a -eq 24 ];then

Upvotes: 2

neuhaus
neuhaus

Reputation: 4094

In bash you can use

if (( a == 24 )); then

Upvotes: 1

Mehdi Yedes
Mehdi Yedes

Reputation: 2375

If you want to access a variable's content, you should use $var.

So in your script, instead of testing the content of the variable a you are changing it's content.

You should use:

if [ $a -eq 24 ]

instead of if a=24.

I suggest you take a look here to get a good grasp of shell variables.

Upvotes: 1

drosam
drosam

Reputation: 2896

Try this syntax for the if

if [ $a -eq 24 ];then

Upvotes: 3

Related Questions