3

I've got variable

network="198.168.1.x"  # for ex. 198.168.1.254

I want to create new variables:

next_serv="198.168.1.(x-1)"  # for ex. 198.168.1.253
max_host="198.168.1.(x-2)"   # for ex. 198.168.1.252

How to do it?

3 Answers 3

6
network="198.168.1.254"
IFS="." read -r a b c d <<< "$network"
next_serv="$a.$b.$c.$(($d-1))"
echo "$next_serv"

Output:

198.168.1.253
4

The easy way is to split the value on the "." markers and do the arithmetic, putting the result together again.

With awk (which handles delimiters and so forth):

this_serv=192.168.1.100
next_serv=$(echo $this_serv | awk -F. '{printf "%d.%d.%d.%d", $1,$2,$3,$4-1}')
0

Using parameter expansion:

$ network="198.168.1.254"                      
$ next_serv="${network%.*}.$((${network##*.} - 1))"
$ max_host="${network%.*}.$((${network##*.} - 2))"

$ echo "$next_serv"
198.168.1.253
$ echo "$max_host" 
198.168.1.252

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .