0

Simple bash script to generate subnet from ip and netmask which i got after some googling.It as below

#!/bin/bash
sub_net()
{
    A=$1
    B=$2
    OFS=$IFS
    IFS="."
    set ${A:-0.0.0.0}
    A1=${1:-0}
    A2=${2:-0}
    A3=${3:-0}
    A4=${4:-0}

    IFS="."
    set ${B:-0.0.0.0}
    B1=${1:-0}
    B2=${2:-0}
    B3=${3:-0}
    B4=${4:-0}

    IFS=$OFS

    C4=$(( B4 & A4 ))
    C3=$(( B3 & A3 ))
    C2=$(( B2 & A2 ))
    C1=$(( B1 & A1 ))

    echo ${C1}.${C2}.${C3}.${C4}
}

sub_net 181.172.0.111 255.255.255.0

i know the IFS usage it's for field separator but at around line:8 the codeset ${A:-0.0.0.0} written so what is use of it. For debugging i just comment that line but got following error

./script.bash: line 33: 255.255.255.0: syntax error: invalid arithmetic operator (error token is ".255.255.0")

Can anyone explain usage of it?

1 Answer 1

1

The line:

set ${A:-0.0.0.0}

would set positional parameters. Since you've said:

IFS="."

before this, it'd imply that if the variable A was 123.42.10.42 then positional parameters 123, 42, 10, 42 would be set which can be accessed using $1, $2, ... (And, indeed, you could see those being utilized in setting other variables: A1, A2, ...)


Regarding the ${A1:-0} notation, you could read about it in Shell Parameter Expansion:

${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.